Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/Redux where to set sessionStorage

I'm working on my first react/redux app and I'm not sure where I should call sessionStorage.setItem(). I'm currently storing user credentials from a loginUserSuccess() action but I'm not sure this is where I should be doing that. Furthermore, I'm using fetch to make requests and would like to add the user's authToken to all requests. I was looking into fetch-intercept but not much documentation is provided for modifying headers.

actions/loginActions.js

export function loginUser(user) {
  return function(dispatch) {
    return LoginApi.login(user).then(creds => {
      dispatch(loginUserSuccess(creds));
    }).catch(error => {
      throw(error);
    });
  };
}

export function loginUserSuccess(creds) {
  sessionStorage.setItem('credentials', JSON.stringify(creds));
  return {
    type: types.LOGIN_USER_SUCCESS,
    state: creds
  }
}

api/packageApi.js

class PackageApi {
  // called on successful login
  static getAllPackages() {
    const request = new Request('/my/endpoint', {
      method: 'GET',
      headers: new Headers({
        'AUTHORIZATION': `Bearer ${JSON.parse(sessionStorage.credentials).authToken}`
      })
    });
    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
}

export default PackageApi;
like image 958
neridaj Avatar asked Jan 10 '18 01:01

neridaj


People also ask

How do you set a value in session storage in react?

// Access value associated with the key var item_value = sessionStorage. getItem("item_key"); // Assign value to a key sessionStorage. setItem("item_key", item_value); Note: All values in Session storage will be stored in string format, hence must be parsed to other data types if required.

Where does redux store the data?

The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.

How does redux store local storage data?

In this step, we will create the react redux store and set up the redux persist inside the react store using the reducers we have created in earlier step. Inside the app/ folder create the store. js file, then inside the file add the give code. To set up the redux store, import the configureStore, and setupListeners.


2 Answers

Taking into consideration Dan Abramov's explanation we have the following:

store/sessionStorage.js

export const loadState = () => {
  try {
    const serializedState = sessionStorage.getItem('state');

    if (serializedState === null) {
      return undefined;
    }

    return JSON.parse(serializedState);
  } catch (error) {
    return undefined;
  }
};

export const saveState = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    sessionStorage.setItem('state', serializedState);
  } catch (error) {
    // Ignore write errors.
  }
};

store/index.js

import { createStore } from 'redux';
import rootReducer from '../reducers';
import { loadState, saveState } from './sessionStorage';

const persistedState = loadState();
const store = createStore(rootReducer, persistedState);

store.subscribe(() => {
  saveState(store.getState());
});

Full explanation: https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage

like image 96
Ronald Araújo Avatar answered Oct 13 '22 14:10

Ronald Araújo


Think about a sessionStorage as just one more store. This store needs to be synced with the Redux one so it works properly. I think the reducer is the right place. That is where you have data changes and data initialization.

like image 2
Krasimir Avatar answered Oct 13 '22 14:10

Krasimir