I can't acces state's values with [...state_name,{}].
I can't solve this problem. I'm trying to set this algorithm for dynamic menu. I'm getting values from useFetch method's List action.
I can get values , its working correctly. Its getting values from json server.
import {useState } from "react";
import useFetch from "../functions/useFetch";
const MenuCreator = () => {
const [menu,setMenu] = useState([]);
const {data} = useFetch('LIST','/menuler');
const [subMenu,setSubMenu] = useState([]);
for(let i in data)
{
if(data[i].main_menu == null){
for(let s in data){
if(data[s].main_menu == data[i].id)
setSubMenu([...subMenu,{id:data[s].id,menu_adi:data[s].menu_adi,main_menu:data[s].main_menu,menu_link:data[s].menu_link}]);
}
setMenu([...menu,{
id:data[i].id,
menu_adi:data[i].menu_adi,
menu_icon:data[i].menu_icon,
menu_link:data[i].menu_link,
subMenus:subMenu
}]);
setSubMenu(null);
}
}
console.log(menu);
return {menu};
}
export default MenuCreator;
Photo for error :
useFetch.js for this solution:
import { useEffect, useState } from 'react';
import {URL} from '../config/conf';
const useFetch = (type,url) => {
if(url === undefined)
url = "/";
const [data,setData] = useState(null);
const [loading,setLoading] = useState(true);
const [error,setError] = useState(null);
switch(type){
case "ADD":
fetch(`${URL+url}`,{
method:"POST",
headers:{"Content-Type":"application/json"},
body:JSON.stringify(data)
}
).then(()=>{
setData("success");
setLoading(false);
})
break;
case "DELETE":
fetch(`${URL+url}`,
{
method:"DELETE"
}).then(()=>{
setData("success");
setLoading(false);
})
break;
case "UPDATE":
break;
case "LIST":
useEffect(()=>{
fetch(`${URL}${url}`).then(res=>{
if(!res.ok) throw Error("Veriler Getirilirken Bir Hata Oluştu");
return res.json();
}).then(data=>{
setData(data);
setLoading(false);
}).catch(err=>{
setError(err.message);
setLoading(false);
})
},[url])
break;
}
return {data,loading,error};
}
export default useFetch;
setSubMenu([]);to reset your submenu. That is use an empty array (which is iterable) rather thannull