Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React reducer – state not accessible within reducer function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading