1
React.useEffect(

() => {
  const users = [  
    {id:123123123,
      name:"mert",
      del: <deleteButton  onClick={()=>console.log(users)} />
    }]
    setusers(users)


}, [])

hello i have a problem I created a useState called [users, setusers] and in useeffect, I have assigned a delete function for each user. this delete function needs to reach users state

But the problem starts here. When I want to reach users through the delete function, I get the initial state of the state, (the state at the time I created the first user object)

  • 1
    Hi! Can you provide the code for the full component in your question? I think it would be helpful for us to have some more code to look at. – Jesse Winton Oct 28 '20 at 21:40
  • From your description it seems that you are shadowing the `users` variable, i.e. your initial `users` array from the `useEffect` is used in the `onClick` rather than the `users` returned from `useState`. In short, you should either rename `const users =[...]` to something else, for example `const initalUsers = [...]` or remove that variable entirely and do `setusers([...])`. – Elias Schablowski Oct 28 '20 at 21:46
  • Does this answer your question? [React: useContext value is not updated in the nested function](https://stackoverflow.com/questions/64259890/react-usecontext-value-is-not-updated-in-the-nested-function) – hackape Oct 28 '20 at 21:47
  • This is yet another stale closure problem. Take a look at [my answer](https://stackoverflow.com/a/64442841/3617380) at another question. The solution also applies to your problem. – hackape Oct 28 '20 at 21:49
  • Put `users` as a dependency to the `useEffect` hook. – BlackMath Oct 28 '20 at 23:28
  • Also, putting JSX (React elements) directly in the state is an anti-pattern. – Emile Bergeron Oct 28 '20 at 23:41

1 Answers1

0

In your useEffect hook you define a const variable called users.
In the onClick Event you output the const variable users and not the state variable users.

Which means const users is not equal to state.users
Rename your const variable 'users' and see if anything changes.

Amel
  • 653
  • 9
  • 15