Skip to content

Instantly share code, notes, and snippets.

@hubgit
Last active November 28, 2018 04:20
Show Gist options
  • Save hubgit/d74f324948e6d416d2a01da906aae35f to your computer and use it in GitHub Desktop.
Save hubgit/d74f324948e6d416d2a01da906aae35f to your computer and use it in GitHub Desktop.
PrivateRoute for React Router v4
const userRequest = () => ({
type: USER_REQUEST
})
const userSuccess = user => ({
type: USER_SUCCESS,
user
})
const userFailure = error => ({
type: USER_FAILURE,
error
})
export const fetchUser = () => dispatch => {
dispatch(userRequest())
return api.get('/me').then(response => {
dispatch(userSuccess(response.user))
}).catch(err => {
console.error(err)
dispatch(userFailure(err.message))
})
}
import React from 'react'
import { connect } from 'react-redux'
import { Redirect, Route, withRouter } from 'react-router-dom'
import { fetchUser } from './actions'
const PrivateRoute = ({ user, fetchUser, component, ...rest }) => (
<Route {...rest} render={props => {
if (!user.complete) {
if (!user.fetching) {
fetchUser()
}
return null // TODO: loading screen
}
if (!user.data) {
return <Redirect to={{
pathname: '/login',
state: {
from: rest.location
}
}}/>
}
return React.createElement(component, props)
}}/>
)
export default withRouter(connect(
state => ({
user: state.user
}),
{
fetchUser
}
)(PrivateRoute))
export const user = (state = {
fetching: false,
complete: false,
error: null,
data: null
}, action) => {
switch (action.type) {
case USER_REQUEST:
return Object.assign({}, state, {
fetching: true,
complete: false,
error: null,
data: null
})
case USER_SUCCESS:
return Object.assign({}, state, {
fetching: false,
complete: true,
error: null,
data: action.user
})
case USER_FAILURE:
return Object.assign({}, state, {
fetching: false,
complete: true,
error: action.error,
data: null
})
case LOGOUT:
return Object.assign({}, state, {
data: null
})
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment