dhj
dhj

Reputation: 4805

How can I chain a state update and a call to refect API data with hooks?

I have a function which is called when a form value changes. Once it has changed, I want to refetch the data from the API. My old setState was doing it this way in a class.

I'd like to use hooks, but I saw there were no promise callbacks when you have a useState set function.

  updateState = name => ({ target: { value } }) => {
    this.setState({ [name]: value }, () => {
      this.doConversion();
    });
  };

If I have something like useEffect() which calls fetchData(); what would be an elegant way to rewrite the above, taking into account the hook goodness in the latest React version?

This seems like a common use case.

Upvotes: 1

Views: 43

Answers (1)

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

I think you can leverage dependencies of hooks

const [dependency,setDependency] = useState({})

useEffect(()=>{
  doConversion();
},[dependency]) // RUN useEffect WHEN DEPEDENCY CHANGES

const someHandler = () =>{
   setDependency({}) // UPDATE STATE
}

Upvotes: 1

Related Questions