If i run my code, dispatch(addPost(formData)); is executed and while thunkAPI is running navigation.navigate('PostList'); is executed and moves to the PostList screen before the actions are finished.
But what i want to do is When I execute the sendPostfunc function, dispatch(addPost(formData)); is firstly triggered, and secondly, thunkAPI.dispatch(postSlice.actions.purePost()); is executed and thirdly, thunkAPI.dispatch(loadPosts()); is executed and the action is complete, after that navigation.navigate('PostList'); I want to make it run and go to the PostList Screen.
How can i fix my code?
this is my code
(Post.tsx)
const sendPostfunc = useCallback(async () => {
dispatch(addPost(formData));
navigation.navigate('PostList');
}, [dispatch,navigation]);
(action.tsx)
export const addPost = createAsyncThunk(
'post/addPost',
async (data: Object, thunkAPI) => {
try {
const response = await axios.post('/post/addPost', data);
thunkAPI.dispatch(postSlice.actions.purePost());
thunkAPI.dispatch(loadPosts());
return response.data;
} catch (error: any) {
return thunkAPI.rejectWithValue(error.response.data);
}
},
);
CodePudding user response:
- Move your
navigate
call intoaddPost
(pass it as an additional argument, something likeredirectTo
, a callback that will execute after posts have been loaded. - Assuming
loadPosts
is also a thunk, let it return a promise so you canawait
this work being done insideaddPost
- explained here: https://redux.js.org/usage/writing-logic-thunks#returning-values-from-thunks