Getting an error with Redux-toolkit , "The object notation for `createSlice.extraReducers` has been removed
Asked Answered
D

1

5

I am trying to use redux-toolkit to store data from an api.I tried it but I am getting this error saying "The object notation for createSlice.extraReducers has been removed. Please use the 'builder callback' notation instead" Here's the code snippet:

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

export const getAllJobs=createAsyncThunk("jobDetails",async ()=>{
    const data = await fetch(" http://localhost:3031/jobs");
    const result = data.json();
    return result
    
})


export const jobDetails=createSlice({
    name:"jobDetails",
    initialState:{
        jobs:[],
        loading:false,
        error:null,
    },
    extraReducers:{
        [getAllJobs.pending]: (state)=>{
            state.loading=true;
        },
        [getAllJobs.fulfilled]: (state,action)=>{
            state.loading=false;
            state.jobs=action.payload;
        },
        [getAllJobs.rejected]: (state,action)=>{
            state.loading=false;
            state.error=action.payload;
        },
    },
})


export default jobDetails.reducer;

and for store

import {configureStore} from '@reduxjs/toolkit'
import  jobDetails  from '../features/jobSlice'


export const store= configureStore({
    reducer: {
        app: jobDetails
    },
})

I am trying to store fetched api data to jobs

Domoniquedomph answered 31/12, 2023 at 17:54 Comment(1)
I tried searching for the error but those solution suggests using builder callback which I don't know how to do.Domoniquedomph
S
14

The object syntax for createSlice.extraReducers has been deprecated since version 1.9.0 and then removed in v2.0.0. It's explained both in v2.0.0 changelogs and in the migration guide to RTK 2.0 and Redux 5.0 how to fix it. As the error says, you have to convert the object into the builder callback syntax:

As an example, this:

const todoAdded = createAction('todos/todoAdded')

createReducer(initialState, {
  [todoAdded]: (state, action) => {}
})

createSlice({
  name,
  initialState,
  reducers: {
    /* case reducers here */
  },
  extraReducers: {
    [todoAdded]: (state, action) => {}
  }
})

should be migrated to:

createReducer(initialState, builder => {
  builder.addCase(todoAdded, (state, action) => {})
})

createSlice({
  name,
  initialState,
  reducers: {
    /* case reducers here */
  },
  extraReducers: builder => {
    builder.addCase(todoAdded, (state, action) => {})
  }
})
Sihonn answered 31/12, 2023 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.