I have a father component containing a function that adds a new object to a useState objectList. This list is iterated over to show a list of child components that contain the information stored in the useState objects. Here’s my father component.
const FatherComponent = (data) => {
const [objectList, setObjects] = useState(data.objects)
const addObject = useCallback(prevObjects => {
setObjects([new Object(data.id, "", ""), ...prevTests])
data.id += 1
}, [data])
useEffect(() => {
data.objects = objectList
console.log(testComponents)
}, [objectList, data])
return(
{objectList.map((object) => (
<ChildComponent
object={object}
objectList={objectList}
setObjects={setObjects}
/>
))}
);
}
class Object {
constructor(
id,
name,
description) {
this._id = id
this._name = name
this._description = description
}
//getters and setters
The console.log
in the useEffect hook returns the correct values whenever a test is added. Suppose I add a test, I write ‘name’ in the name textbox and then I add another text, the console.log will print the following:
0: Object { _id: 1, _name: "", _description: ""}
1: Object { _id: 0, _name: "name", _description: ""}
All should be easy from now on but it isn’t. Here is the code of the child component:
const ChildComponent = (object, objectList, setObjects) => {
//keep an eye on this, I'll talk about it shortly
useEffect(() => {
console.log(object)
}, [])
const [name, setName] = useState(object.name)
const handleName = (event) => {
setName(event.target.value)
}
const [description, setDescription] = useState(object.description)
const handleDescription = (event) => {
setDescription(event.target.value)
}
useEffect(() => {
let newObjectList = [...objectList]
let newObject = new Object(object.id, name, objective)
let index = newObjectList.findIndex(objectComp => objectComp.id === test.id)
newObjectList[index] = newObject
setObjects(newObjectList)
}, [name, description])
return (
<div>
<input type='text' placeholder='Object name' className='nameTextBox'
value={name}
onChange={handleName}>
</input>
<textarea type='text' className='objectTextBox'
value={description}
onChange={handleDescription}>
</textarea>
</div>
);
}
The console.log
executed when the second child component is rendered (the one after writing name in the first child component’s name textbox) prints the following values:
{ _id: 1, _name: "name", _description: ""}
name should be empty and it is the same as the component added before. Adding other components creates the same result. I would like new added components to have empty fields.