I have a useState initialized to an object of type ExampleObject
. This class has many properties (also nested) that make use of javascript’s getters and setters. I use the getters all around my code in order to access the useState’s properties:
const Component = ({data}) => {
const [example, setExample] = useState(ExampleObject(data.p1,data.p2))
return(
{example.property2}
<ChildComponent1
example = {example}
setExample = {setExample}
/>
<ChildComponent2
example = {example}
setExample = {setExample}
/>
)
}
export class ExampleObject {
constructor(p1, p2) {
this._property1 = p1;
this._property2 = p2;
}
get property1(){
return this._property1
}
set property1(property1){
this._property1 = property1
}
get property2(){
return this._property2
}
set property2(property2){
this._property2 = property2
}
Some of my child components update the example useState with its setter. I copy the useState’s content into another variable, update that variable and then use the setter:
const ChildComponent1 = ({example, setExample}) => {
const [textContent, setTextContent] = useState(example.property1)
const handleTextContent = (event) => {
setTextContent(event.target.value)
}
useEffect(()=> {
newExample = { ...example }
newExample.property1 = textContent
setExample(newExample)
}, [textContent, example])
return(
<textarea
value={textContent}
onChange={handleTextContent}>
</textarea>
);
}
This generates a problem, the useStae is updated but its setters are lost making the whole code wrong. example.property2
in the RootComponent hands out an undefined error (should be changed to example._property
) and the same goes for example.property1
. I would like to keep using javascript’s getters as it is good practice to do so. Is there a way to set a useState object without losing them?