Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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))
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading