Home > OS >  How can I control dispatch actions in Redux toolkit with React Native?
How can I control dispatch actions in Redux toolkit with React Native?

Time:05-08

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:

  1. Move your navigate call into addPost (pass it as an additional argument, something like redirectTo, a callback that will execute after posts have been loaded.
  2. Assuming loadPosts is also a thunk, let it return a promise so you can await this work being done inside addPost - explained here: https://redux.js.org/usage/writing-logic-thunks#returning-values-from-thunks
  • Related