Why is setState not working when setting an array?

-1
 const [groups, setGroups] = useState();
         useEffect(() => {
        axios.get(url).then(response => {
          var x = 0;
          var groupss = [];
          response.data.map( gr => {
              if((gr.permissions & 0x00000008) == 8) {
                var url = "https://cdn.url.com/icons/" + gr.id + "/" + gr.icon;
                groupss.push({ 'key': x, 'name': gr.name, 'url': url, id: gr.id })
                x++;
              }
          })
          setGroups(groupss);
          setLoading(false);
          console.log(groups);
          
        });   }, []);

groupss is an array of objects but groups logs as undefined i want it to be the same as groupss but in state i ve tried setGroup with just text and it s still undefined

reactjs
asked on Stack Overflow Feb 13, 2021 by dragos • edited Feb 13, 2021 by dragos

1 Answer

0

Try logging it inside useEffect(() => {console.log(groups)}, [groups]). When you set the state, it doesn't immediately change the groups array, rather, it re-renders the component with the new value of groups.

answered on Stack Overflow Feb 13, 2021 by Silidrone

User contributions licensed under CC BY-SA 3.0