I am trying to replace a state array using a separately given array. I am unable to get my state to update to hold the values of the separate array. I've tried several things
const [userFriendsList, setUserFriendsList] = useState([]);
window.chatAPI.recvFriendsList(message => {
if (message.length > userFriendsList.length)
{
console.log(message)
setUserFriendsList(message);
console.log(userFriendsList)
}
});
const [userFriendsList, setUserFriendsList] = useState({friendsList: []});
window.chatAPI.recvFriendsList(message => {
if (message.length > userFriendsList['friendsList'].length)
{
console.log(message)
setUserFriendsList({friendsList : message});
console.log(userFriendsList)
}
});
const [userFriendsList, setUserFriendsList] = useState([]);
window.chatAPI.recvFriendsList(message => {
if (message.length > userFriendsList.length)
{
console.log(message)
setUserFriendsList([ ... userFriendsList, message]);
console.log(userFriendsList)
}
});
None of these are updating the state.
Edit: Component -
const FriendsList = () =>
{
const [checkFriendsList, setCheckFriendsList] = useState(true)
const [userFriendsList, setUserFriendsList] = useState([]);
window.chatAPI.recvFriendsList(message => {
console.log(message)
setUserFriendsList(oldFriendList => [ ...oldFriendList, ...message]);
console.log(userFriendsList)
});
useEffect ( () => {
if (checkFriendsList)
{
setCheckFriendsList(false);
window.chatAPI.getFriendsList();
}
}, [checkFriendsList])
return (
<div className="friends-list-container">
<List className="friends-list">
<ListItem className="friends-list-title"> Friends List </ListItem>
</List>
</div>
);
}
CodePudding user response:
The problem is in the condition if (message.length > userFriendsList.length)
.
If message
is a non empty-string it will always be longer that your empty userFriendsList
state, remove the condition and update the array with:
const [userFriendsList, setUserFriendsList] = useState([]);
window.chatAPI.recvFriendsList(message => {
setUserFriendsList(oldFriendList => [ ...oldFriendList, message]);
});
If message
is an array just do:
const [userFriendsList, setUserFriendsList] = useState([]);
window.chatAPI.recvFriendsList(message => {
setUserFriendsList(oldFriendList => [ ...oldFriendList, ...message]);
});
CodePudding user response:
try
//if( your condition)
{
setUserFriendsList([ ... userFriendsList, ...message]);
}