Comments (4)
@colinramsay good idea for an example or explanation.
Ultimately it is dependent on your app and what kind of middleware you are using for your API calls which makes an example a little bit tricky. Lets say that you have a fairly standard API middleware such as something similar to redux-api-middleware. This would dispatch actions for fetching, success, and failure. Such as GET_TODOS_FETCH
, GET_TODOS_SUCCESS
and GET_TODOS_FAILURE
. The api middleware would attach the status code inside the payload on failure.
What you could do is create a custom middleware that comes after the api middleware and if it receives an action with a payload.status === 401
then dispatch API_UNAUTHORIZED
. Then inside your reducer:
const userReducer = (state = {}, { type, payload }) => {
switch (type) {
case USER_LOGGED_IN:
return payload;
case API_UNAUTHORIZED: // fall-through
case USER_LOGGED_OUT:
return {};
}
}
You could also easily implement this using a saga, either for listener or implement the middleware API inside a saga and simply dispatch the action from there.
Does that help? I don't have time at the moment to extend the JWT example (or another example) with a resource that could return 401 at times but would be more than happy to review a PR if someone wants to give it a go 😄
from redux-auth-wrapper.
Once the
API_UNAUTHORIZED
hits the userReducer, it clears the user data and causes a re-render in the authWrapper.
This is the (rather obvious) bit I was missing. Thanks. If I get time then I'll try and produce an expanded example as a PR but for now I'm happy to close this issue. Appreciate you taking the time to walk me through this.
from redux-auth-wrapper.
How would dispatching API_UNAUTHORIZED
actually trigger a redirect though?
from redux-auth-wrapper.
@colinramsay Assuming you had the following auth wrapper and route setup:
// Redirects to /login by default
const UserIsAuthenticated = UserAuthWrapper({
authSelector: state => state.user, // how to get the user state
redirectAction: routerActions.replace, // the redux action to dispatch for redirect
wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
})
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<Route path="login" component={Login}/>
<Route path="foo" component={UserIsAuthenticated(Foo)}/>
<Route path="bar" component={Bar}/>
</Route>
</Router>
</Provider>,
document.getElementById('mount')
)
Lets say you are on /foo
and the user had an existing JWT token and the validation of the token on the initial app load or after login dispatched a USER_LOGGED_IN
. Therefore the user data in the store (state.user
) has has some data in it, like { name: 'Demo User' }
. When the user navigates to the /foo
route the authWrapper checks state.user
and the predicate returns true (because the default checks for non empty/null) and renders the Foo Component. Once the API_UNAUTHORIZED
hits the userReducer, it clears the user data and causes a re-render in the authWrapper. This time, the authWrapper predicate returns false, which forces a redirect back to Login.
The redirection would be same as if a user was on the /foo
route and hit a logout button. The API_UNAUTHORIZED
is just a different mechanism for clearing out the data but the redirect logic is identical. You can see that scenario at work in the basic example included in the repo or the JWT example here
from redux-auth-wrapper.
Related Issues (20)
- [Possible Bug] Async Validation in a multi-step form HOT 1
- How to make chunk js with react-router HOT 1
- Error in UserAuthWrapper
- Hande logout when expired token in axios interceptors but not redirect to login page HOT 2
- Misleading naming of authenticatedSelector HOT 2
- Example with react 16.x HOT 1
- Reducer not yet defined HOT 2
- Usage with react-cookies
- not running when am trying do npm start HOT 1
- connectedReduxRedirect is missing HOT 1
- Deprecated lifecycle method in redirect.js HOT 7
- Doesn't work with latest react HOT 3
- Type {} is missing the following properties from type Readonly<InjectedAuthProps> HOT 1
- ES6 Module - Error when using with Electron HOT 2
- redirect.js replace UNSAFE_componentWillMount with componentDidMount HOT 6
- No question mark befor query param on redirect HOT 2
- Versioning Order HOT 4
- React-router v6 HOT 9
- Infinite loop (redirect ) with nesting wrappers HOT 1
- Call for mantainers! HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from redux-auth-wrapper.