Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the result of query from createApi in a slice?

I just integrated to redux-toolkit . My goal is to store the result of the query getPosts in a slice, so I can use it across the site or change it.

My createApi is like this:

  export const postsApi = createApi({
  reducerPath: "posts",
  baseQuery: getGeneralFetchBaseQuery(),
  endpoints: (builder) => ({
    getPosts: builder.query<PostsType, number>({
      query: (id) => `api/posts/${id}`,
    }),
  }),
});

export const { useGetPosts } = postsApi;

I want to store the result from getPosts in this slice

export const postsSlice = createSlice({
  name: "posts",
  initialState,
  reducers: {},
});

export default postsSlice.reducer;

and my store is like this

export const mainStore = configureStore({
  reducer: {
    postsReducer,
    [postsApi.reducerPath]: postsApi.reducer,
  },
})

How can this be achieved?

like image 680
Kimia Khakzad Avatar asked Aug 01 '21 16:08

Kimia Khakzad


1 Answers

Let me preface this by: generally, you probably shouldn't.

RTK-Query is a full cache solution - so you should usually not copy state out of it in most solutions, but let RTK-Query keep control over that data.
If you want to change it, temporarily copy it over into local component state (this goes for all kind of form states by the way, you should not edit a form in-place in redux, but temporarily move it over to local component state), use a mutation to save it back to the server and then let RTKQ re-fetch that data to update the cache. Wherever you need that data, just call useGetPostsQuery() and you're good - if that data is not yet fetched, it will get fetched, otherwise you will just get the value from cache.

Oh, bonus: you should not create an extra api per resource. You should have one single createApi call in your application in almost all cases - you can still split it up over multiple files using Code Splitting.

All that said, of course you can copy that data over into a slice if you have a good use case for it - but be aware that this way you now are responsible for keeping that data up-to-date and cleaning it up if you don't need it any more. Usually, RTKQ would do that for you.

Here is an example on how to clone data from a query over into a slice, taken from the RTKQ examples page:

const slice = createSlice({
  name: 'auth',
  initialState: { user: null, token: null } as AuthState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addMatcher(
      api.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.token = payload.token
        state.user = payload.user
      }
    )
  },
})
like image 58
phry Avatar answered Oct 26 '22 14:10

phry