I'm working on my first React Redux application in typescript and I have a peculiar error in that the object that the reducer is receiving is 'undefined'.
types.ts
//Action typesexport const ADD_FAVOURITE = 'ADD_FAVOURITE'export const REMOVE_FAVOURITE = 'REMOVE_FAVOURITE'//Add favourite actioninterface addFavouriteAction { type: typeof ADD_FAVOURITE, favourite: ImageThumbnail}//Remove favourite actioninterface removeFavouriteAction { type: typeof REMOVE_FAVOURITE, id: string}export type favouriteActionTypes = addFavouriteAction | removeFavouriteActionexport interface favouriteState { favourites: ImageThumbnail[]}export const initialState: favouriteState = { favourites: []}export type rootState = ReturnType<typeof favouriteReducer>
store.ts
export const rootReducer = combineReducers({ favouriteReducer})const store = createStore(rootReducer)export default store
actions.ts
export function addFavourite (image: ImageThumbnail): favouriteActionTypes { return { type: ADD_FAVOURITE, favourite: image }}export function removeFavourite (id: string): favouriteActionTypes { return { type: REMOVE_FAVOURITE, id: id }}
reducers.ts
export function favouriteReducer( state = initialState, action: favouriteActionTypes): favouriteState { switch (action.type) { case ADD_FAVOURITE: console.log(`am here in add fav object is: ${action.favourite}`) return { favourites: [...state.favourites, action.favourite] } case REMOVE_FAVOURITE: return { favourites: state.favourites.filter( favourite => favourite.id !== action.id ) } default: return state }}
The console.log in the reducer always returns an undefined object.
The component that is calling these actions with buttons is as follows. The this.props.imageThumbnail is a valid object that is being passed into the addFavourite/removeFavourite functions.
component.tsx
const mapState = (state: rootState) => ({ favourites: state.favourites})const mapDispatch = { addFavourite: (image: ImageThumbnail) => ({ type: 'ADD_FAVOURITE' }), removeFavourite: (id: string) => ({ type: 'REMOVE_FAVOURITE' })}//component declaration//render method<TouchableOpacity onPress={() => this.props.addFavourite(this.props.imageThumbnail)}/><TouchableOpacity onPress={() => this.props.removeFavourite(this.props.imageThumbnail.id)}/>const connector = connect( mapState, mapDispatch)type PropsFromRedux = ConnectedProps<typeof connector>export default connector(component)