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?
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
}
)
},
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With