Skip to content

Instantly share code, notes, and snippets.

@ericpkatz
Created October 1, 2018 10:58
Show Gist options
  • Save ericpkatz/36583d82490a750b8d59e7c7a04dae4c to your computer and use it in GitHub Desktop.
Save ericpkatz/36583d82490a750b8d59e7c7a04dae4c to your computer and use it in GitHub Desktop.
Client Side Thunks for Token Exchange
const exchangeTokenForAuth = (history)=> {
return (dispatch)=> {
const token = window.localStorage.getItem('token');
if(!token){
return
}
return axios.get('/api/auth', {
headers: {
authorization: token
}
})
.then( response => response.data)
.then( auth => {
dispatch(_setAuth(auth))
if(history){
history.push('/users');
}
})
.catch( ex => window.localStorage.removeItem('token'))
}
}
const logout = ()=> {
window.localStorage.removeItem('token');
return _setAuth({});
}
const login = (credentials, history)=> {
return (dispatch)=>{
return axios.post('/api/auth', credentials)
.then(response => response.data)
.then( data => {
window.localStorage.setItem('token', data.token);
dispatch(exchangeTokenForAuth(history));
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment