'How to set initial state for redux reducer in typescript?
I am getting this TypeScript error Property 'hasError' does not exist on type '(state: ErrorType | undefined, action: ErrorActionType) => ErrorType'. which I think its complaining about setting the initialState for reducer.
import { ErrorType, ErrorActionType } from '../actions';
import { ActionTypes } from '../types';
export const errorReducer = (
state: ErrorType = { hasError: false, errorMessage: '' },
action: ErrorActionType
) => {
switch (action.type) {
case ActionTypes.setError:
return action.payload;
default:
return state;
}
};
and here is my action
import { Dispatch } from 'redux';
import { ActionTypes } from '../types';
export interface ErrorType {
hasError: boolean;
errorMessage: string;
}
export interface ErrorActionType {
type: ActionTypes.setError;
payload: ErrorType;
}
export const setError = (hasError: boolean, errorMessage: string) => {
return (dispatch: Dispatch) => {
dispatch<ErrorActionType>({
type: ActionTypes.setError,
payload: { hasError, errorMessage },
});
};
};
and also my reducer.index
import { combineReducers } from 'redux';
import { errorReducer } from './error';
import { loadingReducer } from './loading';
import { newsReducer } from './news';
import { schoolsReducer } from './schools';
import { StoreStateType } from '../types';
export const reducers = combineReducers<StoreStateType>({
isLoading: loadingReducer,
hasError: errorReducer.hasError,
errorMessage: errorReducer.errorMessage,
news: newsReducer,
schools: schoolsReducer,
});
here is app state type
export interface StoreStateType {
isLoading: boolean;
hasError: boolean;
errorMessage: string;
news: NewsType[];
schools: SchoolType[];
}
Solution 1:[1]
Maybe you can try: hasError typeof false as the parameter.
This is the problem that I encountered when using typescript with reducer and useContext together.
export const setError = (hasError typeof false, errorMessage: string) => {
return (dispatch: Dispatch) => {
...
};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user134097 |