Reputation: 89
I need to simply set a state if the data from the server exists.
const [names, setNames] = useState([...details?.names])
The details object is in the props and is set from the database. details.names
is an array from the server. This works when the details.names object exists but I am having troubles if the names doesnt exist in the details object. If thats the case, setNames to an empty array.
Upvotes: 0
Views: 134
Reputation: 12136
You can use a useEffect
hook to detect a change in the details
variable and trigger a state update:
const [names, setNames] = useState([])
useEffect(() => {
if (details?.names) {
setNames(details.names)
}
}, [details])
Upvotes: 2
Reputation: 4469
You can simply do the following:
const [names, setNames] = useState(details?.names ? [...details?.names] ?? [])
if details?.names
is an array the only thing needed is this:
const [names, setNames] = useState(details?.names ?? [])
So basically use the Nullish coalescing operator, read more about that here:
Upvotes: 2