Skip to content

Instantly share code, notes, and snippets.

@saito-sv
Forked from bruce/Login.js
Created September 28, 2018 05:38
Show Gist options
  • Save saito-sv/a32f02754735f693936b927e3f37fcdb to your computer and use it in GitHub Desktop.
Save saito-sv/a32f02754735f693936b927e3f37fcdb to your computer and use it in GitHub Desktop.
React + Redux + localStorage Login example
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { API_TOKEN } from './constants/LocalStorage';
import { URL } from './constants/URLs';
const networkInterface = createNetworkInterface({uri: URL});
networkInterface.use([{
applyMiddleware(request, next) {
const currentApiToken = localStorage.getItem(API_TOKEN);
if (!currentApiToken) {
next();
return;
}
if (!request.options.headers) {
request.options.headers = new Headers();
}
delete request.options.headers.map;
request.options.headers.Authorization = `Bearer ${currentApiToken}`;
next();
}
}]);
const client = new ApolloClient({
networkInterface,
// other stuff...
});
// ...
// reducers/currentApiToken.js
import { browserHistory } from 'react-router';
import { SET_CURRENT_API_TOKEN, UNSET_CURRENT_API_TOKEN } from '../constants/EventTypes';
import { API_TOKEN } from '../constants/LocalStorage';
const initialState = localStorage.getItem(API_TOKEN);
export default function(state = initialState, event) {
switch (event.type) {
case SET_CURRENT_API_TOKEN:
localStorage.setItem(API_TOKEN, event.value);
window.location = "/";
return event.value;
case UNSET_CURRENT_API_TOKEN:
localStorage.removeItem(API_TOKEN);
window.location = "/";
return initialState;
default:
return state;
}
}
// actions/currentApiToken.js
import { SET_CURRENT_API_TOKEN, UNSET_CURRENT_API_TOKEN } from '../constants/EventTypes';
export function setCurrentApiToken(value) {
let action = {
type: SET_CURRENT_API_TOKEN,
value: value
};
return action;
}
export function unsetCurrentApiToken(value) {
let action = {
type: UNSET_CURRENT_API_TOKEN,
value: value
};
return action;
}
// components/Login/Login.js
class Login extends Component {
// ...
handleSubmit(evt) {
evt.preventDefault();
this.props.mutate(this.state)
.then(({ data }) => {
this.handleLogin(data);
}).catch((error) => {
this.setState({password: null, error: true});
console.warn('there was an error sending the query', error);
});
}
handleLogin(data){
const { result } = data;
if (result && result.token) {
this.setState({error: false});
this.props.setCurrentApiToken(result.token);
}
if (this.state.error) {
this.refs.password.focus();
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment