Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useCookie with TypeScript #26

Open
roborobs1023 opened this issue Sep 7, 2022 · 1 comment
Open

useCookie with TypeScript #26

roborobs1023 opened this issue Sep 7, 2022 · 1 comment

Comments

@roborobs1023
Copy link

When I try using useCoookie with typescript I get errors when it returns a null value for newValue.

Any idea what would be causing this?

@roborobs1023
Copy link
Author

`import { useState, useCallback } from "react"
import { Cookies } from "typescript-cookie"
import { CookieAttributes } from "typescript-cookie/dist/types"

export default function useCookie(name: string, defaultValue: any | undefined) {
const [value, setValue] = useState(() => {
const cookie = Cookies.get(name)
if (cookie) return cookie
Cookies.set(name, defaultValue)
return defaultValue
})

const updateCookie = useCallback(
    (newValue: string | number | boolean | null | undefined, options: CookieAttributes | undefined) => {
        Cookies.set(name, newValue, options)
        setValue(newValue)
    },
    [name]
)

const deleteCookie = useCallback(() => {
    Cookies.remove(name)
    setValue(null)
}, [name])

return [value, updateCookie, deleteCookie]

}`

Here is an option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant