I'm trying to learn redux by making a to-do list
but i am getting an error and i couldn't solve this problem
my types
export interface TodoType {
text: string;
id: number;
}
export interface TodoState {
todoList: TodoType[];
}
interface ADD_TODO {
type: "ADD_TODO";
payload: TodoType;
}
interface REMOVE_TODO {
type: "REMOVE_TODO";
payload: TodoType;
}
export interface AppState {
todo: TodoState;
}
export type TodoAction = ADD_TODO | REMOVE_TODO;
TodoReducer.ts ;
import { TodoState, TodoAction } from "global";
const INITIAL_STATE: TodoState = {
todoList: [],
};
export const TodoReducer = (state = INITIAL_STATE, action: TodoAction) => {
console.log(state, action);
};
index.ts
import { TodoState } from "global";
import { combineReducers } from "redux";
import { TodoReducer } from "./reducers/TodoReducer";
export interface AppState {
todo: TodoState;
}
const rootReducer = combineReducers<AppState>({
todo: TodoReducer,
});
export default rootReducer;
here I am getting error in todo: part
index.ts of my file
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import App from "./App";
import rootReducer from "./store";
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
I will be very glad if you can help me how to solve this problem
CodePudding user response:
Your TodoReducer
should return TodoState
types at all times.
Currently, you are only logging state
and action
inside your reducer. Fill it up and it should work fine.
CodePudding user response:
While it's not quite a direct answer to your question, you should really switch to using our official Redux Toolkit package, which is the standard approach for writing Redux logic. It will simplify your code, let you eliminate all of those extra action and type definitions, and works great with TS:
https://redux.js.org/usage/usage-with-typescript
Example:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from '../../app/store'
// Define a type for the slice state
interface CounterState {
value: number
}
// Define the initial state using that type
const initialState: CounterState = {
value: 0
}
export const counterSlice = createSlice({
name: 'counter',
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
increment: state => {
state.value = 1
},
decrement: state => {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value = action.payload
}
}
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
// Other code such as selectors can use the imported `RootState` type
export const selectCount = (state: RootState) => state.counter.value
export default counterSlice.reducer