A
A
Andriy0222022-01-27 23:22:38
React
Andriy022, 2022-01-27 23:22:38

How to form an array from objects in userReducer?

I need to push the object into an array when I click on the Save button. It doesn't work.

import React, {useReducer} from 'react';

const renders = (animals, action) => {
    switch (action.type) {
        case 'xxx':
            return {...animals, [action.field]: action.payload}

        default:
            return animals
    }
}
const catAndDog = {
    cat: '', dog: ''
}
const Animals = () => {

    const [animals, dispatch] = useReducer(renders, catAndDog)

    const save = (e) => {
        dispatch({
            type: 'xxx',
            field: e.target.name,
            payload: e.target.value
        })
    }
    const animalCat = (e) => {
        e.preventDefault()
        console.log(animals)
    }
    const animalDog = (e) => {
        e.preventDefault()
        console.log(animals)
    }
    return (
        <div>
            <form onSubmit={animalCat}>
                <label>Cat:<input type="text" value={animals.cat} name={'cat'} onChange={save}/></label>
                <button>Save</button>
            </form>
            <form onSubmit={animalDog}>
                <label>Dog:<input type="text" value={animals.dog} name={'dog'} onChange={save}/></label>
                <button>Save</button>
            </form>
            <hr/>
        </div>
    );
};

export default Animals;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-01-28
@0xD34F

const reducer = (state, action) => {
  switch (action.type) {
    case 'update':
      return {
        ...state,
        ...action.payload,
      };

    default:
      return state;
  }
};

const Animals = () => {
  const [ animals, dispatch ] = React.useReducer(reducer, {
    cat: '',
    dog: '',
    mouse: '',
    rhinoceros: '',
  });

  const save = e => {
    e.preventDefault();

    const { name, value } = e.target.querySelector('input');

    dispatch({
      type: 'update',
      payload: {
        [name]: value,
      },
    });
  }

  return (
    <div>
      {Object.entries(animals).map(([ k, v ]) => (
        <form onSubmit={save}>
          <label>
            {k}:
            <input type="text" defaultValue={v} name={k} />
          </label>
          <button>Save</button>
        </form>
      ))}
    </div>
  );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question