Reputation:
I have a code in useEffect (like componentDidMount):
useEffect(()=>{
const idChat = props.match.params.id;
const data = {
idChat,
user: props.user._id
}
authService.getChat(data)
.then(res =>{
const userChat = res.data.users.filter(e=> e!== data.user).toString()
authService.getuser(userChat)
.then(res=>{
setOtherUser(res.data)
})
})
.catch(err=>{
setErrors(err.response)
})
}, [])
This code run once. Ok.
I need another useEffect that use a otherUser
state. But it isn't seted yet.
useEffect(()=>{
socket.readUsers(users => {
const is = users.users.indexOf(otherUser._id);
console.log(users,otherUser._id, is)
if(is < 0){
setUsersStatus(false)
}else{
setUsersStatus(true)
}
});
})
if i do condicitional, never enter into if :/ How can i call otherUser in useEffect?
Upvotes: 0
Views: 78
Reputation: 2806
add otherUser user as this shape in with dependent of the otherUser as second parameter as arry[otherUser]
useEffect(()=>{
if(otherUser){....}
},[otherUser])
Upvotes: 0
Reputation: 18769
Add it as a dependency of the effect. You can then just skip executing the code when otherUser
isn't set.
useEffect(() => {
if (otherUser) {
socket.readUsers(users => {
const is = users.users.indexOf(otherUser._id);
console.log(users, otherUser._id, is);
if (is < 0) {
setUsersStatus(false);
} else {
setUsersStatus(true);
}
});
}
}, [otherUser]);
Upvotes: 1