Добавляем в массив копию исходного объекта:
const defaultAnimals = {
cat: '',
dog: '',
mouse: '',
rhinoceros: '',
};
const animalsReducer = (state, action) => {
switch (action.type) {
case 'updateObj':
return {
...state,
obj: {
...state.obj,
[action.payload.name]: action.payload.value,
},
};
case 'addObjToArr':
return {
...state,
arr: [ ...state.arr, state.obj ],
obj: defaultAnimals,
};
default:
return state;
}
};
const Animals = () => {
const [ animals, dispatch ] = useReducer(animalsReducer, {
obj: defaultAnimals,
arr: [],
});
const onChange = ({ target: { name, value } }) => {
dispatch({
type: 'updateObj',
payload: { name, value },
});
};
const onSubmit = e => {
e.preventDefault();
dispatch({
type: 'addObjToArr',
});
};
return (
<div>
<form onSubmit={onSubmit}>
{Object.entries(animals.obj).map(([ k, v ]) => (
<div key={k}>
<label>
{k}:
<input name={k} value={v} onChange={onChange} />
</label>
</div>
))}
<button>Save</button>
</form>
<pre>{JSON.stringify(animals.obj, null, 2)}</pre>
<pre>{JSON.stringify(animals.arr, null, 2)}</pre>
</div>
);
};
Или, добавляем в массив объект, содержащий значение только одного из свойств исходного объекта:
const animalsReducer = (state, action) => {
switch (action.type) {
case 'updateObj':
return {
...state,
obj: {
...state.obj,
[action.payload.name]: action.payload.value,
},
};
case 'addObjToArr':
return {
...state,
arr: [
...state.arr,
{
animal: action.payload,
name: state.obj[action.payload],
},
],
};
default:
return state;
}
};
const Animals = () => {
const [ { obj, arr }, dispatch ] = useReducer(animalsReducer, {
obj: {
cat: '',
dog: '',
mouse: '',
rhinoceros: '',
},
arr: [],
});
const onChange = ({ target: { name, value } }) => {
dispatch({
type: 'updateObj',
payload: { name, value },
});
};
const onSubmit = (e, animal) => {
e.preventDefault();
dispatch({
type: 'addObjToArr',
payload: animal,
});
};
return (
<div>
{Object.entries(obj).map(([ k, v ]) => (
<form onSubmit={e => onSubmit(e, k)} key={k}>
{k}:
<input name={k} value={v} onChange={onChange} />
<button>Save</button>
</form>
))}
<pre>{JSON.stringify(obj, null, 2)}</pre>
<pre>{JSON.stringify(arr, null, 2)}</pre>
</div>
);
};