react / functional component / props changed / getDerivedStateFromProps

Thread Pitt picture Thread Pitt · Mar 22, 2019 · Viewed 17.4k times · Source

Lets say I'm doing a simple CRUD app in react. My functional component is basically just the form.

  • In the CREATE case I pass in an empty object via props
  • In the UPDATE case I pass in an object with the values via props (I got the data in the parent component with an API call)

I looks like this:

const MyForm = (props) => {

 const [myValues, setMyValues] = useState(props.myValues);
 const [errors, setErrors] = useState(0);
 (...)
}

In the UPDATE case, I run (of course) into the issue that props.myValues is still empty when the component is mounted, and not set again (updated) when the api call from the parent component has finished thus leaving the form values empty.

Using a class component, I'd solve that with getDerivedStateFromProps(). Is there anything like that in a functional component? Or am I doing this wrong from the beginning? Thanks for any advice!

Answer

Vishal picture Vishal · Mar 22, 2019

Yes, you can of course use useEffect.

In your case the code should look like this:

const MyForm = (props) => {

 const [myValues, setMyValues] = useState(props.myValues);
 const [errors, setErrors] = useState(0);

 useEffect(() => {
   setMyValues(props.myValues);
 }, [props.myValues]);

}