Reputation: 21
Currently I am using React, Redux Toolkit and Formik in my current project and the situation is that while i am submitting form data (using useFormik() hook) with help onSubmit method; with in onSubmit method i am calling Redux action (using useDispatch() hook) then access the state data directly using useSlector hook but i am getting always previous value. The sample codes are given below :
const formik = useFormik({
initialValues,
onSubmit : (values) => {
alert(JSON.stringify(values));
dispatch(loginSumbmit(values));
console.log(authState); // get previous data
},
validationSchema,
});
Upvotes: 1
Views: 1627
Reputation: 921
The majority of the time you do this in regards to Formik is to check for validation errors. Assuming you're using createAsyncThunk
from Redux-Toolkit for loginSumbmit
, you can get the payload immediately after and check for errors/success by doing this:
const formik = useFormik({
initialValues,
onSubmit : async (values) => {
const resultAction = await dispatch(loginSumbmit(values));
if (loginSumbmit.fulfilled.match(resultAction)) {
// it was a success, you can check resultAction.payload or use `unwrapResult`
} else {
// there was an error, handle it
}
},
validationSchema,
});
Another option would be:
const formik = useFormik({
initialValues,
onSubmit : values => dispatch(loginSumbmit(values))
.then(unwrapResult)
.then(originalPromiseResult => {
// do something with the success payload
})
.catch(serializedError => {
// do something with the error payload
}),
validationSchema,
});
There is an example of this exact behavior in the docs here: https://redux-toolkit.js.org/api/createAsyncThunk#examples
In general, you should never need an exact snapshot of the store immediately following a thunk in the same tick. Anything that you're trying to get with a selector should be available in the payload that caused the store to change.
Upvotes: 2