arslan_chaudhry
arslan_chaudhry

Reputation: 37

undefined is returned using redux toolkit

I am currently working with the redux toolkit I am facing an issue for the last 2 days. The problem is when I am trying to select a state using the useSelector undefined is returned.

The code is given below:

reducer

import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const SchoolDataReducer = createSlice({
    name: "datasets",
    initialState: [],
    reducers: {
        getSchoolRecords(state, action) {
          
          return action.payload

        }
    }
})
export const { getSchoolRecords } = SchoolDataReducer.actions;
export default SchoolDataReducer.reducer;

export function getDataTriger() {
    return async function getSchoolDataThunk(dispatch, getstate) {
        try {

            const res = await axios.get("/getschool")

            dispatch(getSchoolRecords(res.data))

        } catch (error) {
            console.log(error);
        }
    }
}

store

import { configureStore } from "@reduxjs/toolkit";
import SchoolDataReducer from "./SchoolData"
const store = configureStore({
    reducer: {
        School: SchoolDataReducer
    }
});
export default store;

result

const maindATA = useSelector(State => State.datasets)
console.log(maindATA); // undefined

Upvotes: 1

Views: 385

Answers (1)

Lin Du
Lin Du

Reputation: 102597

Your whole state data structure is { School: [] }, you can get the state slice using useSelector(state => state.School).

Please see https://redux-toolkit.js.org/api/configureStore#reducer about the data structure of the redux state. So you can change the reducer option of configureStore like below:

const store = configureStore({
    reducer: {
        datasets: SchoolDataReducer
    }
});

// In component:
const maindATA = useSelector(state => state.datasets)

Upvotes: 2

Related Questions