Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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[];
}

>Solution :

You can do

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading