Home > Mobile >  useState: destructure nested object with typescript
useState: destructure nested object with typescript

Time:09-28

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):

  • Property 'title' does not exist on type 'ITopic | undefined'
  • Tuple type '[ITopic | undefined, Dispatch<SetStateAction<ITopic | undefined>>]' of length '2' has no element at index '2'.

CodePudding user response:

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: ''
});

CodePudding user response:

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
  • Related