Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active May 6, 2020 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/5248c77d5d22a40d53c2bb8a80c40654 to your computer and use it in GitHub Desktop.
Save tzkmx/5248c77d5d22a40d53c2bb8a80c40654 to your computer and use it in GitHub Desktop.
useCsrfToken hook for csrf token stored in meta of document
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