0

Like this example: constructing-a-dynamic-base-url-using-redux-state, I need to get the data of a certain endpoint from the cache to build fetch arg, I can get the data by api.endpoints.getPost.select(postId)(getState()), But how do I ensure that the getPost request has been sent?

const api = createApi({
  baseQuery: fetchBaseQuery(),
  endpoints: (builder) => ({
    getPost: builder.query({
      query: (id) => `/posts/${id}`,
    }),
    getBook: builder.query({
      async queryFn(postId, { dispatch, getState }) {
        // could I use this?
        await dispatch(api.endpoints.getPost.initiate(postId))
        const { data: post } = api.endpoints.getPost.select(postId)(getState())
        // ...
        // use post.xxx to fetch books...
        myFetch(`/books/${post.xxx}`)
      },
    }),
  }),
})
Mxcpanel
  • 95
  • 7

1 Answers1

1

In the current RTK 1.7 beta you can just const result = await dispatch(api.endpoints.getPost.initiate(postId)).unwrap().

But what you are doing here generally looks very dangerous. There is no mechanism in place that will re-run getBook after getPost returns a different result in the future. Things will probably get out of sync this way.

Dependent queries should probably better be handled in a custom hook with two useQuery hook calls, where the second hook call gets a part of the result from the first call as an argument.

phry
  • 35,762
  • 5
  • 67
  • 81