Galivan
Galivan

Reputation: 5328

useState: destructure nested object with typescript

I'm trying to destructure an object in useState so I can directly use the properties. But I am not sure about the correct syntax to use with typescript.

Here is the interface for "topic":

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

Without destructuring it would look like:

const [topic, setTopic] = useState<ITopic>()

To destructure, I have tried a few things,for instance this doesn't work:

const [{title, text, posts}: ITopic, setTopic] = useState<ITopic>();

It says (if I hover over title and setTopic):

Upvotes: 0

Views: 420

Answers (2)

Enfield Li
Enfield Li

Reputation: 2530

The second approach is to add a check in the forms of loading data:

const [topic, setTopic] = useState<ITopic | undefined>() 
// explicitly define the type as "undefined", which is unnecessary, but a good indicator

if(!topic) return <div>loading</div>;

const {title, text, posts} = topic; // then you can safely destructure the object

Upvotes: 1

Andrew
Andrew

Reputation: 7545

Use an initial value. Because you don't have an initial value, it detects on the first render that this cannot be destructured.

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

const [{title, text, posts}, setTopic] = useState<ITopic>({
    posts: [],
    text: '',
    title: ''
});

Upvotes: 3

Related Questions