hernandeΩ
hernandeΩ

Reputation: 89

Set state if the array exists

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

Answers (2)

Gian Marco Toso
Gian Marco Toso

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

Emanuele Scarabattoli
Emanuele Scarabattoli

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:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Upvotes: 2

Related Questions