In my app I have the following state/reducer setup:
const initialState = {
inputValues: {
username: "",
fullName: "",
email: "",
password: ""
},
inputValidities: {
username: false,
fullName: false,
email: false,
password: false
},
formIsValid:false
}
const [state, dispatch] = useReducer(reducer, initialState);
I then call dispatch to update the state:
dispatch({type: "handleInputChanged", payload: {id, value, validationResult: result}})
My reducer looks like so:
export function reducer(state, action) {
switch(action.type) {
case "handleInputChanged":
const {id, value, validationResult} = action.payload
console.log(state.inputValues);
}
}
When attempting to log state.inputValues, an error ooccurs stating: Cannot read properties of undefined (reading ‘inputValues’).
How am I able to access the current state input values? Thanks.
>Solution :
As per the documentation…
reducer: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state
Your reducer doesn’t return anything which means it returns undefined. If your reducer is called multiple times, for example by using <StrictMode>, subsequent calls will receive the state returned by previous calls.
At the very least, you could return the existing state
export function reducer(state, action) {
switch(action.type) {
case "handleInputChanged":
const {id, value, validationResult} = action.payload
console.log(state.inputValues);
}
return state; // or { ...state }
}