Lets say I'm doing a simple CRUD app in react. My functional component is basically just the form.
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!
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]);
}