Last active
December 17, 2018 22:52
-
-
Save olegpolyakov/33b0d47d9b14dca7e8491b2bbe2f67ab to your computer and use it in GitHub Desktop.
JWT for React
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 React from 'react'; | |
let cachedToken; | |
function setToken(token) { | |
cachedToken = token; | |
localStorage.setItem('authToken', token); | |
} | |
function getToken() { | |
if (!cachedToken) { | |
cachedToken = localStorage.getItem('authToken'); | |
} | |
return cachedToken; | |
} | |
function removeToken() { | |
cachedToken = null; | |
localStorage.removeItem('authToken'); | |
} | |
function isAuthenticated() { | |
return !!getToken(); | |
} | |
axios.post('https://localhost:5000/api/auth', { 'Authorization': `Bearer ${token}` }) | |
.then(response => response.data) | |
.then(token => setToken(token)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment