Any idea on how to make this work?
Thanks!
CodePudding user response:
no that is wrong React.useState(defaultValue)
it's just the default value for the React.useState
which is used on component render and it does not listen for new changes.
You need to use React.useEffect()
hook which takes the dependencies array if you leave the dependencies array empty then useEffect
will only be invoked once on component render but if you pass dependency as your redux data then every time your dependency data is changed useEffect
will be invoked.
So finally you code will be like this
const dispatch = useDispatch();
const userData = useSelector(state => state.user);
const initialValues = {
color: 'Green',
};
const [ formValues, setFormValues ] = useState(initialValues);
React.useEffect(()=>{
setFormValues((userData.length > 0) ? userData : initialValues);
// cleanup function which will be invoked on component unmount
return ()=> {
setFormValues(userData)
}
},[useData]);
console.log(JSON.stringify({ userData, formValues }));
const onSubmit = (values) => {
dispatch(userActions.save(values));
};
CodePudding user response:
I don't know what is the correct way to capture the new stored value. But what i can suggest is to create a useEffect hooks to set new form values that runs every time userData
changes.
useEffect(() => {
setFormValues(userData)
}, [userData])