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[];
}
>Solution :
You can do
const [post, setPost] = useState<TitleAndDescription>({
title: data?.title ?? '',
content: data?.content ?? []
});