implement logout using Redux+TypeScript

一世执手 提交于 2020-04-18 05:49:41

问题


I have a login page, which redirects to a private /panel page if the login is successful and an accessToken is returned. I'm using Redux store to check for the token in the privateRoute component.

Problems I'm facing:

  • I want to implement logout from the /panel page using the exit icon. If I try to add another reducer in the combined reducer, I get TypeScript errors.

  • What would be the best way to implement logout from the exit icon? Should I use the same tokenReducer add a LOGOUTcase in the switch? The accessToken from the store needs to be deleted somehow. For deleting the payload in the state, should I use filter? But where exactly?

  • Since I'm using persist, the accessToken remains in the local storage. So even if I reload the codesandbox (or terminate and re-run my app in localhost), the next time, I will be able to access /panelwithout even logging in.

CodeSandbox:

https://codesandbox.io/s/frosty-shannon-0ivez?file=/src/store/reducers/index.ts

Email: c@c.com

Password: check

The only main difference is that instead of manually writing the accessToken, in the original code, I am running a GraphQL mutation. If the login is successful, an accessToken is returned and dispatched like this:

 dispatch({ type: 'LOGIN', payload: data.loginEmail.accessToken });

where loginEmailis the mutation and accessTokenis the string returned. If someone could copy the Sandbox and guide me, that would be great.


回答1:


For the "where to store the token" part: As we know we usually store a sessionID or something in the cookie as an identifier for the server to keep the user's session. If we need to store some other token, mostly we still use cookie, like how laravel and axios treat csrf-token: store in cookie, send it in header when sending an xhr request, or place it as a hidden input in a form (so it gets sent along with other form fields).

Don't quite get other parts of the question but, I'd say structure your redux store code however you like, as long as they are clean, readable, easy to maintain.



来源:https://stackoverflow.com/questions/61227075/implement-logout-using-reduxtypescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!