EN VI

Javascript - Disptach action inside Redux RTK API Slice?

2024-03-14 15:00:06
How to Javascript - Disptach action inside Redux RTK API Slice

I wonder if it possible to dispatch an action from another reducer in the API Slice of Redux RTK. Assuming I have this

getSomething: builder.query<SomeProps, void>({
        query: () => ({
            url: "...",
            headers: {
                'Content-Type': 'application/json',
            }
        }),

Is it possible to have something in there like onSuccess (assuming the getSomething() returns a 200/anything that resolves to a success)

getSomething: builder.query<SomeProps, void>({
        query: () => ({
            url: "...",
            headers: {
                'Content-Type': 'application/json',
            }
        }),
        onSuccess: (response: SomeProps, {dispatch}) => {
            dispatch(someActionFromAnotherReducer(response))
        }

Solution:

You can do it by using onQueryStarted

A function that is called when you start each individual query or mutation. The function is called with a lifecycle api object containing properties such as queryFulfilled, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { messageCreated } from './notificationsSlice'

export interface Post {
  id: number
  name: string
}

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: '/',
  }),
  endpoints: (build) => ({
    getPost: build.query<Post, number>({
      query: (id) => `post/${id}`,
      async onQueryStarted(id, { dispatch, queryFulfilled }) {
        // `onStart` side-effect
        dispatch(messageCreated('Fetching post...'))
        try {
          const { data } = await queryFulfilled
          // `onSuccess` side-effect
          dispatch(messageCreated('Post received!'))
        } catch (err) {
          // `onError` side-effect
          dispatch(messageCreated('Error fetching post!'))
        }
      },
    }),
  }),
})

See also: RTK Query: dispatch inside query or mutations

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login