Search code examples
reduxredux-thunkredux-api-middleware

How do I use Redux API Middleware and Thunk to chain API requests


I have a couple of RSAA actions like so:

export const getUserById = id => ({
  [RSAA]: {
    endpoint: "...",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    types: [
      GET_USER_BY_ID_REQUEST,
      GET_USER_BY_ID_SUCCESS,
      GET_USER_BY_ID_FAILURE
    ]
  }
});

export const getUserPosts = id => ({
  [RSAA]: {
    endpoint: "...",
    method: "GET",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    types: [
      GET_USER_POSTS_REQUEST,
      GET_USER_POSTS_SUCCESS,
      GET_USER_POSTS_FAILURE
    ]
  }
});

What do I have to do to use thunk (I think) to chain these two actions?

I could create a third action called getUserThenPosts? But what would that look like?


Solution

  • Use redux-thunk and create a third action called getUserThenPosts.

    export const getUserThenPosts = id => dispatch => {
      return dispatch(getUserById(id))
        .then((payload) => {
          return dispatch(getUserPosts(payload.someIdFromUserPayload)));
        };
    };
    

    I'm assuming that getUserPosts requires an argument from the user payload.