I want to copy only those property which is already declared in useState
array, like this:
const SellDashBoard = () => {
const[userData, setUserData] = useState({
name: '',
age: '',
number: '',
})
const data = {
name: 'Ram',
age: '21',
village: 'pithawaiaya'
}
useEffect(() => {
setUserData((pre) => {
return { ...pre, ...data }
})
}, [])
return (
<div>
</div>
)
}
The result is: { name: "Ram", age: "21", number: "", village: "pithawaiaya" }
I want result as userData
{ name: "Ram", age: "21", number: "" }
.
4
Answers
Your excpected output state you wanna be excact similar with your
data
obj, so the best solution i think is to declare thedata
obj in your currentuseState
and delete theuseEffect
hook.You will place the
data
obj outside from yourcomponent
–SellDashBoard
or you can move it in outside file and you can import it as well.Keep every other thing in the object the same and update only the other attributes that you want to change.
We can also make a function that returns an updated object and then we can use useState to update new object. All we are doing in the method is comparing the two objects with the
keys
and if the key exists in theuseState
object then simply update that and leave everything else. I think this should do the job.Instead of shallow copying all of the
data
object’s properties into theuserData
state, create a shallow copy of the previous state to update and iterator over thedata
object’s keys to explicitly check if it is a property of the state, and if it is, overwrite the property.Example:
You can create a function that will check if the key in useState exist in data then copy it if not then empty string. Try this implementation