Where to store access-token in react.js?

前端 未结 3 1878
有刺的猬
有刺的猬 2021-01-31 05:35

I am building an app in Reactjs. I have to make fetch call, after verifying the access_token. On signup, access_token are acquired from back-end server. But, where to store thes

3条回答
  •  清酒与你
    2021-01-31 06:24

    Michael Washburn has a really good article on how to persist your state with redux, here on his webpage

    In the article, he has a link to a very descriptive video tutorial created by Dan Abramov, one of the co-authors of Redux, I followed along with him to add it to my project. Here is the code I used to make it work:

    store.js

    import { createStore, combineReducers } from "redux";
    import { UserReducer, CopyReducer } from "../reducers";
    import { loadState, saveState } from "../utils/localStorage";
    
    export const giveMeStore = () => {
      const reducers = combineReducers({
        copy: CopyReducer,
        user: UserReducer
      });
      const persistedState = loadState();
      const store = createStore(reducers, persistedState);
      //user contains the TOKEN
      store.subscribe(() => {
        saveState({
          user: store.getState().user
        });
      });
      return store;
    };
    

    localStorage.js

    export const loadState = () => {
      try {
        const serializedState = localStorage.getItem("state");
        if (serializedState === null) {
          return undefined;
        }
        return JSON.parse(serializedState);
      } catch (err) {
        return undefined;
      }
    };
    export const saveState = state => {
      try {
        const serializedState = JSON.stringify(state);
        localStorage.setItem("state", serializedState);
      } catch (err) {
        //ignoring write erros
      }
    };
    

    and add the store to the provider:

    import React from "react";
    import ReactDOM from "react-dom";
    import { Provider } from "react-redux";
    
    import { giveMeStore } from "./store.js";
    
    const Root = () => {
      return (
        
          //... your components
          //...
        
      );
    };
    
    ReactDOM.render(, document.querySelector("#root"));
    

提交回复
热议问题