Home > other >  Data fetched from server not loading into redux store?
Data fetched from server not loading into redux store?

Time:09-01

I'm fetching data from a mongoDB database and then fetch that data from the server and finally render the data to the UI in a specified component. I'm using redux-toolkit for state management. The problem is when fetching the data from the server it is not visible in the store. Why is the empty array in the initial state still empty after fetching the data? I'm using createSlice Api that generates the action creators and action types and createAsyncThunk Api for the asynchronous task of fetching the data from the server.

Slice reducer

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

const initialState = {
    realestate: [],
    isSuccess: false,
    isLoading: false,
    message: '',
}

export const getRealEstates = createAsyncThunk(
    'realestate/getRealEstates', async () => {
        try {
            const response = await axios.get('castles')
            return response.data
        } catch (error) {
            console.log(error)
        }
    }
)


export const estateSlice = createSlice({
    name: 'realestate',    
    initialState,
    reducers: {
        reset: (state) => initialState,
    },
    extrareducers: (builder) => {
        
        builder.addCase(getRealEstates.pending, (state) => {
            state.isLoading = true
        })
        builder.addCase(getRealEstates.fulfilled, (state, action) => {
            state.isLoading = false
            state.isSuccess = true
            state.realestate = action.payload
        })
         builder.addCase(getRealEstates.rejected, (state, action) => {
            state.isLoading = false
            state.isError = true
            state.message = action.payload
        })
    }
})

export const { reset } = estateSlice.actions
export default estateSlice.reducer

Store

export const store = configureStore({
reducer: {
    realestate: realestateReducer,
    registered: registerReducer,
  },
});

Component

const realestates = useSelector(state => state.realestate)
const { isLoading, realestate, isError, message, isSuccess} = realestates

const dispatch = useDispatch()

useEffect(() => {
    dispatch(getRealEstates())
        if(realestate){
            setShow(true)
        }else{
            console.log('No data retrieved')
        }
    
}, [dispatch, isError, realestate, message])

CodePudding user response:

It's extraReducers with an uppercase R, your code contains extrareducers.

  • Related