javascriptreduxredux-toolkitrtk-query

RTK Query Mutation with selector


I've used redux toolkit for a few years and I'm pretty familiar with it. I'm going through and attempting to update old code using the newer RTK Query strategy to replace some of my old slices and thunks.

If I'm understanding the docs correctly, it seems like RTK Query is meant to largely replace the old way of doing things, and instead of maintaining state "manually" in your slices, you let RTK Query handle management / caching, and you just re-request the data from the api slice that was defined by RTK Query, and it just does the rest automagically.

Assuming this to be correct, how do you select data that was added to the cache by a mutation?

Specifically, I'm using a mutation to authenticate a user (this is the simplest test scenario, so there's really no auth, no tokens, etc.)

It looks like:

    loginUser: builder.mutation<UserServiceResult, UserCredentials>({
        query: ({ userName, password }) => ({
            url: '/authenticate',
            method: 'POST',
            body: { UserName: userName, Password: password },
        }),
    }),

In the login form, this is used like this:

    const [loginUser, { isLoading: isUpdating }] = useLoginUserMutation();
    loginUser(credentials).unwrap().then((userServiceResult) => {
        if (userServiceResult.isSuccessful) {
            console.log("Successfully logged in", userServiceResult);
            toast.success("User authenticated.", {position: "top-right"});
        } else {
            toast.error("User authentication failed.", {position: "top-right"});
        }
    })

This is all working fine. But the main layout is using a redux selector to check if the user exists in the store in order to show the "logged in" menu vs. the "guest" menu. It looks like this:

const user = useAppSelector(selectUser); // then do stuff if user is not null

What's the strategy for getting data held in the API mutations?

enter image description here


Solution

  • I suspect you could use a fixed cache key to share mutation results across hook instances. See Shared Mutation Results for details.

    In the component doing the log-in, provide a fixed cache key for the mutation.

    const [loginUser, { isLoading: isUpdating }] = useLoginUserMutation({
      fixedCacheKey: "authenticated-user",
    });
    
    ...
    
    loginUser(credentials).unwrap()
      .then(....)
    

    Call the useLoginUserMutation in the target component and provide the same fixed cache key and that component can access the cached data.

    const [, { data: user }] = useLoginUserMutation({
      fixedCacheKey: "authenticated-user",
    });
    
    ...
    
    user?.results?.[0] // { id: "f9a41496-f...", role: 0, userName: "admin", ... }