I am trying to build a searchbar for my project. I have this part of code which shows possible search results, and when you press on one of the names on the list it loads it on a variable and calls the searchUser function.
{filteredData.length != 0 && (
<div className="dataResult">
{filteredData.slice(0, 10).map((user, key) => {
return (
<p className="dataItem" onClick={() => setSelectedUser(user), searchUser}>
{user.Username}
</p>
);
})}
</div>
)}
And the following is searchUser
function searchUser() {
console.log(selectedUser);
setUsername(selectedUser.Username);
setWhomies(selectedUser.Whomies);
setPoints(selectedUser.Points);
setOpenPopup(true);
};
How I can send the selected user to the function which have to show me all his data?
CodePudding user response:
If you want the search to be triggered whenever the value of selectedUser
is updated, you can use the useEffect
hook, because trying to do it on the click event might not work due to synchronization issues.
You can do that as follow:
useEffect(() => {
searchUser();
}, [selectedUser]);
And as a result, you only need to call setSelectedUser
on the click event:
onClick={() => setSelectedUser(user)}
You can check the Effect Hook documentation for more information about it.
CodePudding user response:
setSelectedUser
will update the relevant state in the next render but you're trying to use it synchronously.
Two ways to fix this:
Run an effect when the state changes:
useEffect(() => { setUsername(selectedUser.Username); setWhomies(selectedUser.Whomies); setPoints(selectedUser.Points); setOpenPopup(true); }, [selectedUser]) <p className="dataItem" onClick={() => setSelectedUser(user)}>
Pass the new user as an argument to
searchUser
:function searchUser(user) { setUsername(user.Username); setWhomies(user.Whomies); setPoints(user.Points); setOpenPopup(true); }; <p className="dataItem" onClick={() => { setSelectedUser(user) searchUser(user) }}>...