LoginSignup
1
0

【TypeScript】'xxxxxxx' is possibly 'null'

Posted at

はじめに

Typescript初学者です。
何度も遭遇するエラーだったのでまとめておきました。
調べてよかったです。

'xxxxxxx' is possibly 'null'.

現状

以下のところでエラーが出ました。

titleRef.current.value = data.title; //'titleRef.current' is possibly 'null'
descriptionRef.current.value = data.description; //'descriptionRef.current' is possibly 'null'.

これはtitleRef.currentdescriptionRef.currentのところでnullになるかもしれない。nullは想定してないよとTypeScriptが教えてくれている。

以下のようになっている。

const editPage = ({ params }: { params: { id: number } }) => {
  const router = useRouter();
  const titleRef = useRef<HTMLInputElement | null>(null);
  const descriptionRef = useRef<HTMLTextAreaElement | null>(null);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    toast.loading("編集中...........", { id: "1" });
    await editBlog(
      titleRef.current?.value,
      descriptionRef.current?.value,
      params.id
    );

    toast.success("編集に成功しました!", { id: "1" });

    router.push("/");
    router.refresh();
  };

  useEffect(() => {
    getBlogById(params.id)
      .then((data) => {
        console.log(data);
        titleRef.current.value = data.title;
        descriptionRef.current.value = data.description;
      })
      .catch((err) => {
        toast.error("エラーが発生しました。", { id: "1" });
      });
  }, []);

解決策

パターンの1

titleRef.current!.value = data.title;
descriptionRef.current!.value = data.description;

!は後で必ずtitleRef.currentに入ってくるよという意味

パターン2

if (titleRef.current && descriptionRef.current) {
  titleRef.current.value = data.title;
  descriptionRef.current.value = data.description;
}

if文を使い対応する。こっちの方が直感的で見やすい印象

おわりに

自分のアウトプットのための投稿になるので他の方に役立たないかもしれません。
間違っておりましたら教えていただきたいです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0