1

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
1
  • You've a typo, the state is state.School, so instead of const maindATA = useSelector(State => State.datasets) it should be const maindATA = useSelector(State => State.School). Voting to close as " Not reproducible or was caused by a typo". Commented Jan 11, 2023 at 10:14

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.