最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RTK Query Mutation with selector - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Mar 28 at 14:28 user101289user101289 10.5k18 gold badges93 silver badges163 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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", ... }
发布评论

评论列表(0)

  1. 暂无评论