Mohamed faruk
Mohamed faruk

Reputation: 59

undefined error for the text box using usereducer hooks

Am learning use reducer hooks. Below code, I have facing an issue with an undefined error while executing. There is two text box. If I type the text it has to show the results. But here, after submitting the form. Am getting the undefined message for both the text box. Let me know what I have made the mistakes.

function ReducerFour() {
const initialState = {
    users: [
      { name: 'alan', age: 30 },
      { name: 'messi', age: 30 }
    ]
  };


const ADD_USER = 'ADD_USER';

const appReducer = (state, action) => {
  switch (action.type) {
    case ADD_USER:
      return {
        users: [
          ...state.users,
          { 
            payload: action.payload
          }
        ]
      };
  }
};


  const [state, dispatch] = useReducer(
    appReducer,
    initialState
  );


  const addUser = () => {
    const name = document.getElementById('form-name-input')
      .value;
    const age = document.getElementById('form-age-input')
      .value;

    const newUser = { name, age };

    dispatch({
      type: ADD_USER,
      payload: newUser
    });
  };

  return (
    <div className="app">
      {state.users.map(user => (
        <div>{`${user.name}   ${user.age}`}</div>
      ))}
      <div className="form">
        <div className="form-name">
          <label>name:</label>
          <input id="form-name-input" />
        </div>
        <div className="form-age">
          <label>age:</label>
          <input id="form-age-input" />
        </div>
        <button onClick={() => addUser()}>Add user</button>
      </div>
    </div>
  );
}

export default ReducerFour

Upvotes: 1

Views: 40

Answers (1)

Nilesh Patel
Nilesh Patel

Reputation: 3317

here is the fix.

const appReducer = (state, action) => {
    switch (action.type) {
      case ADD_USER:
        return {
          users: [
            ...state.users,
              action.payload
          ]
        };
        default:
          return state;
    }
  };

Upvotes: 1

Related Questions