2

I can see response object containing array of users , but it seems setState doesn't work inside useEffect() hook.

This is request code.

     const [users,setUsers] = useState([]);
     const getUsers=async()=>{
         await axios.get(API_URL,{
             headers:{
                 'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'Access-Control-Allow-Origin': '*'
             }
         })
         .then((res)=>{
            const data = res.data.users;
             console.log(data);
            setUsers([...users,data]);
            console.log(users);
            
         })
         .catch((err)=>{
             console.log(err);
         })
     }
     useEffect(()=>{
         
         getUsers();
     },[])
wangdev87
  • 8,611
  • 3
  • 8
  • 31
Makarand
  • 477
  • 1
  • 7
  • 17
  • 1
    Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Ajeet Shah Feb 22 '21 at 17:10

1 Answers1

5

setUsers() is the asynchronous method, and you can't get the updated value of users immediately after setusers().

setUsers([...users,data]);
console.log(users); // This will console old value of users

You should use useEffect with adding a users dependency to check the updated value of users.

useEffect(() => {
  console.log(users);
}, [users]);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • Thank you @WilliamWang for your response. – Makarand Feb 22 '21 at 16:14
  • When 'users' is passed in dependency array of useEffect() i get more number of users than i actually have – Makarand Feb 23 '21 at 07:32
  • `useEffect(() => { getUsers(); }, [users]) ` – Makarand Feb 23 '21 at 07:33
  • 1
    no, just add one more useEffect to console.log. you should do getUsers() in the useEffect with no dependency. – wangdev87 Feb 23 '21 at 08:27
  • Now I am able to get users array but cannot access its properties eg, `users.forEach((user)=>console.log(user))` produces array of users, but `users.forEach((user)=>console.log(user.firstname))` prints undefined. – Makarand Feb 23 '21 at 09:09