React-boilerplate: Implementing JWT authentication. Attempting to dispatch action from service

yangyue12306 注册会员
2023-01-26 02:01

Maybe a better approach would be to store the token on the localStorage so that you don't need to access the Redux store to obtain it. Just fetch the token and store it this way:

localStorage.setItem('token', JSON.stringify(token))

Later in your service, just retrieve like this:

const token = JSON.parse(localStorage.getItem('token'));

If you don’t feel safe storing the token in the local storage, there's also the secure-ls package, that allows encryption for the data saved to the local storage.

wangjz38257372 注册会员
2023-01-26 02:01

There is multiple way to do that

1- Export the store

create new store.js

import { createStore } from 'redux';
import reducer from './reducer';
//you can add your middleware, sagas, ...
const store = createStore(reducer);

export default store;

import it to your service and use it everywhere but you’ll end up with a single store for all of your users

  • Cons:

  • Pros: Easy to use

2- You can add your func to middleware and intercept an action

edit your create store code and add new middleware for authorization

const refreshAuthToken = store => next => action => {
  const token = makeSelectAccessToken();
  if (!token) throw new Error('No access token found.');

  if(new Date(token.expires) - Date.now() <= 0) {
    // you can dispatch inside store

  // continue processing this action
  return next(action);

const store = createStore(
  ... //add to your middleware list
  • Cons: Maybe you can need redux-thunk library if this middleware not solve your problem (its easy job. You can't say this even a con)

  • Pros: Best and safer way for your need and it will work everytime you call an action. It will works like a charm on SSR apps

3- or you can send store as parameter to your request method from component

  • Cons: Not the best way it will run after your components initialize and you can make easily mistake or can forget to add to your component.

  • Pros: At least you can do what you want

About the Author

Question Info

Publish Time
2023-01-26 02:01
Update Time
2023-01-26 02:01