I'm trying to store some information every time that a change occurs on the value of a input element.
const [inputs, setInputs] = useState({})
const addInput = (name, value, type) => {
setInputs(() => {
inputs[name] = {
"value": value,
"type": type
}
return inputs
})
}
...
const handleInput = (event) => {
addInput(props.name, event.target.value, event.target.type)
...
}
I've got an empty object callled inputs, and if the user types inside an input like this:
<input name="username" value={onChange} type="text">
the inputs object should have now a property called username:
{
username: {
type: "text",
value: : "text-from-the-user",
}
}
but my problem is: When I add two inputs or more inside this inputs object, a override occurs in all the properties that isn't having a change.
For example: If I have two objects inside the inputs...:
{
username: {
type: "text",
value: : "John",
},
email: {
type: "email",
value: : undefined,
},
}
...and I add some text in the email input, the inputs object loses the data from the username object:
{
username: {
type: undefined,
value: : undefined,
},
email: {
type: "email",
value: : "Jhon123@yahoo.com",
},
}
So I'm trying to implement the ...prev inside this setInput, but I'm having trouble with this, because inside this setInput I say that I want to create new objects if they don't exist:
...
inputs[name] = {
"value": value,
"type": type
}
...
You should do it like this:
setInputs((ps) => ({
...ps,
[name]: {
"value": value,
"type": type
}
}))
When you set state:
useState overwrites new value over the old one (doesn't merge like it was in class components)