Last active
May 6, 2020 10:28
-
-
Save tzkmx/5248c77d5d22a40d53c2bb8a80c40654 to your computer and use it in GitHub Desktop.
useCsrfToken hook for csrf token stored in meta of document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useEffect, useState } from 'react' | |
export function useCsrfToken(cookie: boolean = true): [string, (string) => void] { | |
const head = useRef(document.head) | |
const [csrfToken, setCsrfToken] = useState<string>('') | |
function updateCsrfToken (newToken) { | |
head.current.getElementsByTagName('meta')['csrf-token'].content = newToken | |
setCsrfToken(newToken) | |
} | |
useEffect(() => { | |
const token = cookie | |
? document.cookie.match(/XSRF-TOKEN=([^;]+);/)[1] | |
: head.current.getElementsByTagName('meta')['csrf-token'].content | |
setCsrfToken(token) | |
}, [csrfToken]) | |
return [csrfToken, updateCsrfToken] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment