LoginSignup
2
0

More than 1 year has passed since last update.

[react-cookie]useCookiesでセットしたばかりのcookieを取得できない

Last updated at Posted at 2022-06-26

👇のライブラリを使用した際に詰まったのでメモ
https://github.com/reactivestack/cookies/tree/master/packages/react-cookie

const [cookies, setCookie] = useCookie(['cookieName'])

setCookie('key', 'value')
cookies.key // => undefined

cookiesはuseCookie呼び出し時点のcookieの値がセットされた"[x: string]: any"型のオブジェクトに過ぎないため、useCookie後にセットした値は取り出せない。
undefinedとなる。

const [cookies, setCookie] = useCookie(['cookieName'])

setCookie('key', 'value')
cookies.key // => undefined

const [newCookies, _] = useCookie(['cookieName'])
newCookies.key // => 'value'

👆のように再度useCookieを呼び出せば、セットした値を取り出せる。
が、あまりきれいな書き方ではないので、そもそも設計が間違っているのかもしれない。

2
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
2
0