55
60

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React / Next】postした後に、SWRでfetchして表示している部分を更新させたい

Last updated at Posted at 2022-06-19

個人的な備忘録です。

やりたいこと

  • モーダルなどで記事をpostした後に、後ろで表示されている一覧を更新させたい

環境

  • React: 17.0.2
  • Next: 11.1.3
  • @chakra-ui/react: ^1.8.5

解決方法

  • submit ボタンを押した時に post して、そのpost後に submit メソッド内で SWR の mutate を呼ぶ
  • もし props で渡す場合、 refresh={() => mutate()} などとして渡す

サンプルコード

const { data, error, mutate } = useSWR(~~~);

<Modal
  refresh={() => mutate()}
/>
interface Props {
  refresh: () => Promise<HogeResponse | undefined>
}

export const Modal = ({ refresh }) => {
  const submitHandler = async () {
    // 省略 await
    refresh();
    onClose();
  }
}

参考

55
60
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
55
60

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?