Redux toolkit RTK query mutation not getting returning data
Asked Answered
B

3

7

Hi I recently learned the new react toolkit with the rtk query tool, and I am trying to put in a login system together using the createApi from the rtk package.

After giving it a test on the login button pressed, I see the network request going through without any issue(status code 200), and I get a response object providing user, token, however, when I try to get the returning data using useLoginMutation I get an undefined value.

below is the code for my endpoint which is injected in a base api:

export const apiLogin = theiaBaseApi.injectEndpoints({
  endpoints: (build) => ({
    loginUser: build.mutation<UserReadonly, loginValuesType | string>({
      query: (values: loginValuesType, redirect?: string) => {
        const { username, password } = values;
        const header = gettingSomeHeaderHere

        return {
          url: "login",
          method: "GET",
          headers,
          crossDomain: true,
          responseType: "json",
        };
      },
    }),
  }),
});

export const { useLoginUserMutation } = apiLogin

then inside my React component I destructure the mutation result such like below:

const [login, {data, isLoading}] = useLoginUserMutation();

const submitLogin = () => {
  // pass in username password from the form
  login({username, password});
}

Suppose if I console log out data and isLoading I assume that I will see data: {user: "abc", token: "xyz"}, because under network tab of my inspect window I can see the response of this network request, but instead I am seeing data: undefined

Does any have experience on solving this?

Bennir answered 28/8, 2021 at 1:46 Comment(0)
B
7

Oh I found the reason, it was a very careless mistake. I had to wrap the reducer to my store, which was what I was missing

Bennir answered 28/8, 2021 at 2:30 Comment(0)
L
1

In my case the issue was that I was trying to access the UseMutationResult object inside onClick callback. And the object was not updating inside the callback, even though in the component the values were accurate.

If I put the log outside it's working just fine. here is an example for better understanding (inside handleAddPost the mutationResult is not updating)

Here is a code sample (in case link is not working):

const Component = () => {
  const [addPost, mutationResult] = useAddPostMutation();
  ...
  const handleAddPost = async () => {
      ...
      console.log("INSIDE CALLBACK isLoading and other data is not updating:");
      console.log(JSON.parse(JSON.stringify(mutationResult)))
      ...
  };
  // in the example this is wrapped in an useEffect to limit the number of logs
  console.log(mutationResult.data,"OUTSIDE CALLBACK isLoading and other data is working:")
  console.log(JSON.parse(JSON.stringify(mutationResult)))

  return (
  ...
    <Button
      ...
      onClick={handleAddPost}
    >
      Add Post
    </Button>
...
Lipsey answered 16/9, 2022 at 13:2 Comment(1)
Thanks for this, it resolved my issue! I briefly considered this option but then forgot about this possibility until I saw your answer.Hypogeous
U
0

try fixedCacheKey for mutations

export const ComponentOne = ({username, password}) => {
  // Triggering `login` will affect the result in both this component,
  // but as well as the result in `ComponentTwo`, and vice-versa
  const [login, {data, isLoading}] = useLoginUserMutation({
    fixedCacheKey: 'login',
  });

  const submitLogin = () => {
    // pass in username password from the form
    login({username, password});
  }

  return <div>...</div>
}

export const ComponentTwo = () => {
  const [login, {data, isLoading}] = useLoginUserMutation({
    fixedCacheKey: 'login',
  });

  return <div>...</div>
}
Ultra answered 5/2 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.