How do I store the input data as objects in an array using useState
? Please help.
I need help. I am not able to get the desired output to display the input values.
const Form = () => {
const [allNotes, setAllNotes] = useState([{}]);
const [notes, setNotes] = useState({
name: "",
age: "",
class: "",
request: "",
});
const nameChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, name: event.target.value };
return newState;
});
};
const ageChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, age: event.target.value };
return newState;
});
};
const classChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, class: event.target.value };
return newState;
});
};
const requestChangeHandler = (event) => {
setNotes((prevState) => {
const newState = { ...prevState, request: event.target.value };
return newState;
});
};
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = {
...prevState,
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
};
return newState;
});
};
CodePudding user response:
Everything looks good, maybe except for two small mistakes:
Let's make the initial state for
all notes
just an empty array, likeconst [allNotes, setAllNotes] = useState([]);
The new array inside the
setAllNotes
should be array not object, like:
const submitHandler = () => {
setAllNotes((prevState) => {
const newState = [
...prevState,
{
name: notes.name,
age: notes.age,
class: notes.class,
request: notes.request,
}
];
return newState;
});
};
Hope this makes it work!