Home > other >  Way to avoid non-null assertion while using useState in async Data?
Way to avoid non-null assertion while using useState in async Data?

Time:01-08

Trying to use strict typescript with Next.js and React-query

There is problem that useQuery's return data is Post | undefined. So I should make data given with useQuery not null with ! operator while allocating to useState

ESlint does not like non-null type assertion. I know I could turn it off... But I want to do strict type check so I don't want to avoid this.

One way that I found was to use if statement to do null check but React Hooks is not able to wrap it with if statement...

Is there any brilliant way to do it?

My code is like this

const Edit = () => {
    const router = useRouter();
    const { id } = router.query;

    const { data } = useQuery<Post>('postEdit', () => getPost(id as string));

    const [post, setPost] = useState<TitleAndDescription>({
        title: data!.title,
        content: data!.content,
    });
    const editMutation = usePostEditMutation();
    return (
        <MainLayout>
            <Wrapper>
                {data && <Editor post={post} setPost={setPost} />}
            </Wrapper>
        </MainLayout>
    );
};

export interface TitleAndDescription {
    title: string;
    content: Descendant[];
}

CodePudding user response:

You can do

const [post, setPost] = useState<TitleAndDescription>({
    title: data?.title ?? '',
    content: data?.content ?? []
});

CodePudding user response:

The non-null assertion is for cases when you want to exclude null or undefined values from the type. For most cases you don't need it, you can cast to the type you want:

(data as Post).title

or provide a fallback value:

data?.title || ''
  •  Tags:  
  • Related