I have two reducers inside a combine reducer, and when I call an action to change the state of reducerSrc, my state of reducerTherm get undefined and I receive an error. How can I fix this?
combine:
const rootReducer = combineReducers({
therm: reducerTherm,
src: reducerSrc,
});
export type RootState = ReturnType<typeof rootReducer>;
export const store = createStore(rootReducer);
reducerTherm:
interface Props {
therm: string;
}
const initialState: Props = {
therm: "",
};
export default function reducerTherm(state: Props = initialState, action: any) {
switch (action.type) {
case "SEARCH_THERM":
return action.payload;
break;
default:
return state.therm;
}
}
reducerSrc:
export interface Props {
src: any;
}
const initialState: Props = {
src: "source teste",
};
export default function reducerSrc(state: Props = initialState, action: any) {
switch (action.type) {
case "ADD_SRC":
return action.payload;
break;
default:
return state;
}
}
useEffect watching the therm changing and with this active the action to reducerSrc:
const therm = useSelector((state: RootState) => state.therm);
const src = useSelector((state: RootState) => state.src);
useEffect(() => {
if (therm) {
try {
getPhotosPlaces("shopping")
.then((res) => res.json())
.then((data) => {
store.dispatch({
type: "ADD_SRC",
payload: data,
});
});
} catch (error) {
console.log(error);
}
}
}, [therm]);
The error:
**Unhandled Rejection (Error): When called with an action of type "ADD_SRC", the slice reducer for key "therm" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.**
CodePudding user response:
In the default case of your therm reducer you have
return state.therm; // possibly undefined
Surely you mean to be returning the reducer state (not the key therm
)
return state; // returns { therm: ... }