WebDevSimplified / useful-custom-react-hooks

1.95k stars 687 forks source link

useCookie with TypeScript #26

Open roborobs1023 opened 2 years ago

roborobs1023 commented 2 years ago

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 commented 1 year ago

`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.