skip to Main Content

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.

  1. I am trying to use redux toolkit in order to interact with userToken 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 the userToken value updated in localStorage, Redux will automatically update the component for me using useEffect(() => {...}, userTokenWhichRetrivedFromRedux).
  2. I couldnt find any information on the doc for how to use mutation and combine it with redux toolkit! I used to use redux-saga which I called redux actions after a success or fail request/response.

Question: so I am asking all the knowledgeable fellows out there:

  1. What is the best practice here?
  2. 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


  1. If I understood correctly you need to achieve two things:

    1. Extract the token received from the login mutation and store it in a different redux slice
    2. Change that value every time local storage changes

    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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search