I have created an api slice like this:
export const authSlice = createApi({
reducerPath: "auth",
baseQuery: fetchBaseQuery({
baseUrl: resolveApiBaseUrl(),
prepareHeaders(headers) {
headers.set("Content-Type", "application/json")
headers.set("X-XSRF-TOKEN", <string>resolveUserToken())
return headers
}
}),
endpoints(builder) {
return {
login: builder.mutation<GymAppResponse, Login>({
query: (payload) => ({
url: "/login",
method: "POST",
body: payload
}),
})
}
})
export const {
useLoginMutation,
} = authSlice
I am getting the user token after login action and store it in localStorage so I can limit user access to some part of my application.
- I am trying to use
redux toolkit
in order to interact withuserToken
and as default state for userToken I want to use localStorage value. So I dont want to write code in my component to check the localStorage and do the necessary logic. I want to use redux so when theuserToken
value updated in localStorage, Redux will automatically update the component for me usinguseEffect(() => {...}, userTokenWhichRetrivedFromRedux)
. - I couldnt find any information on the doc for how to use
mutation
and combine it with redux toolkit! I used to useredux-saga
which I calledredux actions
after asuccess
orfail
request/response.
Question: so I am asking all the knowledgeable fellows out there:
- What is the best practice here?
- Unfortunately
redux-persist
is not being actively maintained and I have to use localStorage prgramatically. Is there a package or best practice for handling data which we need to persist after an Api call ?
2
Answers
If I understood correctly you need to achieve two things:
For the first part, I think you can achieve this using the onQueryStarted utility which allows you to await for the login query to be finished and also gives you access to the dispatch function so you can perform other actions to any other slice.
EDIT: Now that I’ve seen phry’s answer – yes a better solution would be matching the query fulfilled event with an extra reducer.
For the second part, this may be a little more complicated but I’ve gotten it to work once using the storage event. Basically, add an event listener for the local storage somewhere at the top-level of your application and then update the token every time the event is fired, i.e. using the same action as in the previous step to initially fill the local storage.
You can find relevant examples here in the RTK Query "examples" section
As I understand it, you want to adjust Redux state as the result of a mutation. In that case, the easiest way of doing that would be adding an
extraReducer
for the mutation fulfilled action to your slice.As for redux-persist: That library is pretty much "finished" years ago – it does not need a lot of active maintenance to be useful, especially giving it’s pluggable nature. You should be perfectly fine using that.