Home > Back-end >  Calling a function after state is set
Calling a function after state is set

Time:01-27

I have noticed that hooks set functions are asynchonous but I need to call a function once my new value has been set.

This is how my state looks:

const[agenda, setAgenda] = useState([{ id: "0", date:new Date(2022,0,21,13,25,0), titulo: "Test 1", obs:'Lorem ipsum dolor sit amet', prioridade:1,local:'-',lugar:'', diatodo:false  },
{ id: "1", date:new Date(2022,0,21,13,25,0), titulo: "Test 2", obs:'Lorem ipsum dolor sit amet', prioridade:1,local:'-',lugar:'', diatodo:false  }])

It's an array so I don't know how to do it, I have tried doing this:

setAgenda({[...agenda,obj]},testFunction);

Visual Studio Code gives me the following error though: Error

How should I do it? Thanks in advance

CodePudding user response:

This is an invalid way of setting the state.

The function for setting the state only take one argument.

If you want a function to run when the state changes you will have to use the useEffect hook. This useEffect hook will have the state as a dependency.

useEffect(() => {
  //do stuff


}, [agenda]);

Also, if you defined your function the same component, you will have to do one of those 3 things (your choice):

  • Write the function directly inside the useEffect.
  • Add the function as a dependency of useEffect.
  • Wrap the function with a useCallback.

https://reactjs.org/docs/hooks-effect.html

https://reactjs.org/docs/hooks-state.html

https://reactjs.org/docs/hooks-reference.html#usecallback

  •  Tags:  
  • Related