The issue I’m facing though is that I want to mimic the behaviour of the FlaskLogin current_user in React throughout the component treed. For anyone that’s not familiar with FlaskLogin, current_user
just stores a session of the user who’s currently logged in.
To do this, I decided on using the React context api. What I do is at the top level component, I wrap a UserProvider around the app as so:
<UserProvider value={this.state.user}>
// Main Component.
</UserProvider>
The state is defined in the constructor:
constructor() {
super();
this.state = {
user: {
id: -1,
username: ‘test username’,
email: 'test email’,
},
};
}
And then I call an Ajax request in the componentDidMount to grab the current_user.
componentDidMount() {
const state = this;
post('/get_current_user').then(function success(data) {
state.setState({
user: {
id: data.data.id,
username: data.data.username,
email: data.data.email,
},
});
}).catch(function exception() {
throw new Error('Failed to grab current user.');
});
}
I can grab this updated context throughout the app. This works great for an “ProfilePicture” component as it grabs the correct state but it doesn’t work for setting the initial values with Formik. In Formik I am creating an update username and email form. The issue is that Formik gets the context api values BEFORE the context api has been updated through the AJAX request. So “test username” will show up in the username field and “test email” will show in the email field. My Formik form is as follows:
const UserSettingsProfileForm = () => {
return (
<UserConsumer>
{context => (
<Formik
initialValues={{ email: context.email, username: context.username }}
validationSchema={userSettingsFormSchema}
onSubmit={userSettingsOnSubmit}
render={userSettingsForm}
>
</Formik>
)}
</UserConsumer>
);
};
Does anyone have any suggestions on how to fix this so the correct context api values show up?
enablereinitialize
prop to true. jaredpalmer.com/formik/docs/api/… – PorterhouseenableReinitialize
(mind the capital 'R') – Everyday