Skip to content

Instantly share code, notes, and snippets.

@zonzujiro
Last active July 15, 2019 12:23
Show Gist options
  • Save zonzujiro/e3a4fee02ff64eb5c174de9fc4767bce to your computer and use it in GitHub Desktop.
Save zonzujiro/e3a4fee02ff64eb5c174de9fc4767bce to your computer and use it in GitHub Desktop.
export let axiosInstance = axios.create({
headers: { 'bearer': jwtToken }
})
export const updateInstance = newToken => {
const settings = {
...(newToken & { headers: { 'bearer': newToken } }),
baseUrl: 'google.com'
}
axiosInstance = axios.create(settings)
}
export const sendGetRequest = url => axiosInstance.get(url)
import { updateInstance } from '/api-layer'
import { FETCH_USER_ERROR } from '/user';
import { FETCH_VIDEOS_ERROR } from '/videos'
const initState = {
jwtToken: null
}
export const updateToken = newToken => {
updateInstance(newToken);
return {
type: UPDATE_TOKEN,
payload: { jwtToken: newToken }
}
}
export const resetToken = () => {
updateInstance(null);
return { type: RESET_TOKEN }
}
const authentication = (action, state = initState) => {
switch(actiion.type) {
case FETCH_USER_ERROR:
case FETCH_VIDEOS_ERROR:
return action.payload.error.statusCode === 401 ? { ...state, jwtToken: null } : state
}
}
import { fetchUsers } from './redux/users'
const mapStateToProps = state => {
isAuthenticated: Boolean(state.authentication.jwtToken)
}
const mapDispatchToProps = { fetchUsers }
class SomeComponent extends React.Component {
componentDidMount() {
const { isAuthenticated, fetchUsers } = this.props;
if (isAuthenticated) {
fetchUsers()
}
}
render() {
const { isAuthenticated, fetchUsers } = this.props;
return isAuthenticated ? <div class='content'/> : <div class='access-denied' />
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent)
import { get } from './api-layer';
import { resetToken } from './authentication'
export const FETCH_USER_ERROR = 'FETCH_USER_ERROR'
export const fetchUsers = () => async dispatch => {
dispatch(fetchingUsers());
try {
const { data } = await get('/users');
dispatch(fetchingUsersSuccess(data.items))
} catch(e) {
dispatch(fetchingUsersError(e))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment