Ishaq Kamran
Ishaq Kamran

Reputation: 223

React State not updating immediatly

I am trying to retrieve data from api and show it in my array but when i setting it up in my useState, it is not updating else it is updating after the 1st render means on the 2nd render and on the first render it is returning the previous state.

Here is my code:

const getMembers = async (id) => {
    const groupMembers = await getGroupMembers(id);
    setLoading(true);
    setMembersData(groupMembers);
    if(membersData){
      const result = usersList.filter(e => !membersData.some(a => a.userId === e.id));
      setRemainingUsers(result);
      console.log(result)
    } else {
      setUsersList(usersList)
    }
    setLoading(false);
  };
let options = remainingUsers.map(function(user){
    return { value: user.id, label: user.username}
  })

What i want is to get remaining users value on the first time function is called and it is updating after the first render. I tried using useEffect but it didn't help. I also search on the google regarding this but almost all solutions are to use useEffect. Here is how i use the useEffect hook.

useEffect(() => {console.log(groupId, group, remainingUsers)}, [ groupId, group, remainingUsers ]);

Upvotes: 0

Views: 83

Answers (1)

MIAㅜ_ㅜ
MIAㅜ_ㅜ

Reputation: 81

If(memebersData) {}

if(groupmembers){
const result = usersList.filter(e => !groupmembers.some(a => a.userId === e.id));
}``` 

Upvotes: 1

Related Questions