When the parent component renders a child component, the parent component uses setState and passes the result to child, if whats passed /from setstate function is expected to be an object, I would make the default value an empty object, otherwise its confusing and i would think bad practice. However, then i always get an err as when child is first rendered there is no value yet, so it only gets an empty object which is no a falsy value. Only thing i can do then in the child component to use Object.keys().length to check if >1 and only then render the passed value. That, again, feels like bad practise too because I unnecessary iterate over (perhaps lots of keys) just to check if I got a not empty object.
What would be the best solution here / good practise? Thanks
const App = () => {
const [value, setValue] = useState({}) //expecting an object
useEffect(() => {
api.get....
setValue(response)
})
return <Child value={value}/>
}
const Child = ({value}) => {
return (
{
value && <div>{value}</div> //that will always throw an error as first time Chuld is rendered it gets an empty object
//this works:
value.Object.keys().length > 0 && <div>{value}</div>
}
)
}
CodePudding user response:
I like to treat a state object as null first, so then you can actually check if there's an object, or if it is null at first;
const [value, setValue] = useState(null);
Null is used to explicitly tell that something is not there. An empty object means that you have an object but without any properties, but is still an object, so any validation of the state like !!{}
will be truthy since the object exists, but without values. Null does not exist so any !!null validation will always return a falsey condition.