How to handle pending fulfilled and rejected states in async reducers

0 votes
Can you explain How to handle pending, fulfilled, and rejected states in async reducers?
Mar 17 in Node-js by Nidhi
• 12,580 points
54 views

1 answer to this question.

0 votes

With Redux Toolkit (Built-in Handling):

Use createAsyncThunk to automatically generate pending, fulfilled, and rejected action types.

Example:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const fetchData = createAsyncThunk('data/fetch', async () => {

  const res = await fetch('/api/data');

  return res.json();

});


const dataSlice = createSlice({

  name: 'data',

  initialState: { loading: false, data: null, error: null },

  extraReducers: (builder) => {

    builder

      .addCase(fetchData.pending, (state) => {

        state.loading = true;

        state.error = null;

      })

      .addCase(fetchData.fulfilled, (state, action) => {

        state.loading = false;

        state.data = action.payload;

      })

      .addCase(fetchData.rejected, (state, action) => {

        state.loading = false;

        state.error = action.error.message;

      });

  },

});

answered Mar 18 by Tanvi

Related Questions In Node-js

0 votes
1 answer

How to Handle Errors for Async Code in Node.js

To handle errors in the correct way ...READ MORE

answered Dec 17, 2024 in Node-js by Navya
117 views
0 votes
0 answers

How to handle async operation challenges in React with redux-saga?

Can i know How to handle async ...READ MORE

Mar 19 in Node-js by Ashutosh
• 23,230 points
25 views
0 votes
1 answer

How to handle async form submissions in React using redux-saga?

To handle async form submissions in React ...READ MORE

answered 5 days ago in Node-js by anonymous
44 views
0 votes
1 answer

How to improve user experience in React using async workflows?

It involves optimizing how your application handles ...READ MORE

answered Mar 18 in Node-js by Anvi
39 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to update state based on async action outcomes in reducers?

To manage asynchronous actions (e.g., API calls), ...READ MORE

answered Mar 18 in Node-js by Tanvi
73 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP