1

Can I access POST mutation response from another component? That is, is it cached like a Query/GET request?

  1. API with POST/mutation createTest to server:

    Of note, I do not have a GET request endpoint to GET Tests, unfortunately.

    export const testApi = createApi({
      reducerPath: 'testApi',
      baseQuery: fetchBaseQuery({ baseUrl: TEST_API_BASE_PATH }),
      tagTypes: ['Test'],
      endpoints: (builder) => ({
        createTest: builder.mutation<
          CreateTestResponse,
          CreateTestRequest
        >({
          query: (payload) => ({
            url: '',
            method: 'POST',
            body: payload,
          }),
          invalidatesTags: ['Test'],
        }),
      }),
    });
    
    export const { useCreateTestMutation } = testApi;
    
  2. Payload is an object retrieved from a form component.

  3. POST returns a response.

    For example:

    {
        data: {
            firstName: "Bluey",
            lastName: "Heeler"
        }
    }
    
  4. I call createTest in a component like this:

    const SomeComponent = ({ payload }) => {
        const [createTest] = useCreateTestMutation();
    
        const someCallback = useCallback(() => {
            try {
                const testResult = createTest(payload);
    
                // do stuff with Test Result
    
            } catch (err) {
                // do stuff with error
            }
        }, [...]);
    
    
        return (
            <div>
                ...
                <Button onClick={someCallback} />
                ....
            </div>
        )
    }
    
  5. I would like to get the result/response of that mutation in another component, similar to the cached response from a GET request/useQuery. Do you know how?

  6. I have resorted to creating an RTK Slice and setting the response there in global state. I get the feeling that that is not the "correct" way of using RTK Query, however.

1 Answer 1

1

You need to explicitly set a cache key if you want to share mutation results.

export const ComponentOne = () => {
  // Triggering `updatePostOne` will affect the result in both this component,
  // but as well as the result in `ComponentTwo`, and vice-versa
  const [updatePost, result] = useUpdatePostMutation({
    fixedCacheKey: 'shared-update-post',
  })

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

export const ComponentTwo = () => {
  const [updatePost, result] = useUpdatePostMutation({
    fixedCacheKey: 'shared-update-post',
  })

  return <div>...</div>
}
Sign up to request clarification or add additional context in comments.

1 Comment

Heh, so my answer wasn't incorrect, it was just incomplete. 😉

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.