0
votes

Hello everyone I has a problem,

this is codeSilce.ts file

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


const codeSlice = createSlice({
  name: "codeApply",
  initialState: {
    codeOTP: "",
    token: "",
  },
  reducers: {
    addcode: (state, action) => {
      state.codeOTP = action.payload;
    },
    setToken: (state, action) => {
      state.token = action.payload;
    },
  },
});

export const { addcode, setToken } = codeSlice.actions;

export default codeSlice.reducer;

this is reducer file

import codeSlice from 'app/slices/codeSlice';

const rootReducer = {
    code: codeSlice
};

export type reducer = typeof rootReducer;

export default rootReducer;

this is store

import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";


const store = configureStore({
  reducer: rootReducer,
});

export default store;

I use this in my file but it has some bug

import { reducer } from 'app/reducers'
const codeState = useSelector((state: reducer) => state.code)

const code = codeState.codeOTP; // wrong here
const token = codeState.token; // and here

this bug is

Property 'codeOTP' does not exist on type 'Reducer<{ codeOTP: string; token: string; }, AnyAction>'.

I don't know why this happening, I have console.log(codeState) but it is an object

1

1 Answers

0
votes

Your issues come from a misunderstanding here.

const rootReducer = {
    code: codeSlice
};

export type reducer = typeof rootReducer;

{code: codeSlice} is a reducer map object. It is an object that maps the properties of the state to their individual reducers. It is not a reducer. A reducer is a function.

Everything is fine on the javascript side of things because configureStore can accept this ReducersMapObject for the reducer property. But you have issues with basing your typescript types off of it.

Redux-toolkit exports some helpful utility types that you can use. Note that the type that you want in your useSelector is the type of the state, not the reducer.

import codeSlice from 'app/slices/codeSlice';
import { StateFromReducersMapObject } from "@reduxjs/toolkit";

// a reducer map object
const rootReducer = {
    code: codeSlice
};

// the state for this reducer map
export type State = StateFromReducersMapObject<typeof rootReducer>;

export default rootReducer;

This type State evaluates to:

type State = {
    code: {
        codeOTP: string;
        token: string;
    };
}