1
function App() {
  const [LinkList, setLinkList] = useState([]);
  const [categories, setCategories] = useState({id:[], cat:[]});
  var catArray = [];

  useEffect(() => {
    fetch("http://127.0.0.1:8000/api/service/category-list/")
      .then((response) => response.json())
      .then((data) => {
        for (var i = 0; i < data.length; i++) {
          catArray.push({id:data[i].id, cat:data[i].category});
        }
        setCategories(catArray);
        console.log(categories); //this line displays empty array
        console.log(catArray)//this line literally displays the date fetched.
       if( setCategories(catArray)){
        console.log(true); //it rejects this line of code
       }else{
        console.log("false");//this line is executed
       }
      });
  
  }, []);

I've put the issue in the comment of code -->{id: Array(0), cat: Array(0)} the above line is displayed when I try to log "categories" to the console please share me your Idea on this problem. code is literally correct, but it still throwing error to the console

  • setState is an async operation and will not be reflected immediately – Rajesh Sep 16 '22 at 06:38
  • change it like this `.then((data) => { for (var i = 0; i < data.length; i++) { catArray.push({id:data[i].id, cat:data[i].category}); } }) setCategories(catArray); console.log(categories);` to not update the state immediately – monim Sep 16 '22 at 07:04

0 Answers0