Formik values are not updated after React setData() hook call.
const INITIAL_VALUES = { users: [ { value: 'admin' } ] };
const CreateUsersHooks = ({ httpClient }) => {
const [ data, setData ] = useState(INITIAL_VALUES);
useEffect(() => {
const fetchUsers = async () => {
const result = await httpClient.get(`${ROUTE_PATH.DOC}/${DOC_ID}`);
console.log('useEffect - setData', usersToFormik(result.data.doc));
setData(usersToFormik(result.data.doc));
};
fetchUsers();
}, []);
console.log('initialValues', data);
return (
<div style={{ padding: '25px 50px' }}>
<Formik
initialValues={data}
onSubmit={onSubmit}
validateOnChange={false}
render={({ values }) => {
console.log('values.users', values.users);
return (
<Users users={values.users} />
);
}}
/>
</div>
);
};
In the browser console I see the following log output:
inititialValues >
{ users: [ { value: 'admin' } ] }
values.users >
{ users: [ { value: 'admin' } ] }
useEffect - setData >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
inititialValues >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
values.users >
{ users: [ { value: 'admin' } ] }
I expected to see the following log in the console (the last line is different)
inititialValues >
{ users: [ { value: 'admin' } ] }
values.users >
{ users: [ { value: 'admin' } ] }
useEffect - setData >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
inititialValues >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
values.users >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
| Software | Version(s) |
| ---------------- | ---------- |
| Formik | 1.5.2
| React | 16.8.6
| TypeScript | No
| Browser | Chrome v73.0.3683.103
| npm/Yarn | yarn v1.13.0
| Operating System | macOS v10.14.4
I put the code in codesandbox https://codesandbox.io/s/y2o6w9vk79?fontsize=14
See the log in the browser console
data before return >
{ users: [ { value: 'admin' } ] }
render - values >
{ users: [ { value: 'admin' } ] }
data before return >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
render - values >
{ users: [ { value: 'admin' } ] }
Expected
data before return >
{ users: [ { value: 'admin' } ] }
render - values >
{ users: [ { value: 'admin' } ] }
data before return >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
render - values >
{ id: '123', users: [ { value: 'trex' }, { value: 'velociraptor' } ] }
My bad, I have to set enableReinitialize={true} in Formik
Most helpful comment
My bad, I have to set
enableReinitialize={true}inFormik