localstorage with React Redux

Asked

Viewed 227 times

0

Good morning, I’m doing a test with React-Redux and localstorage .. it works normal however if I give F5 on the page it does not recover the data that was being saved in localstorage.. someone knows what q might be?

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) {
      // ignore
    }
  }

store js.

import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import * as Sentry from '@sentry/react';
import rootReducer from './reduces';
import {saveState, loadState} from './localStorage';

const initalState = {};

const middleware = [thunk];
const sentryReduxEnhancer = Sentry.createReduxEnhancer (
  {
    // Optionally pass options
  }
);

const store = createStore (
  rootReducer,
  initalState,
  composeWithDevTools (applyMiddleware (...middleware), sentryReduxEnhancer),
  loadState ()
);

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

export default store;

types js.

export const GET_TESTE= 'GET_TESTE';
export const SALVA_TESTE= 'SALVA_TESTE';
export const TESTE_ERROR='TESTE_ERROR';

testeReducer.js

import {GET_TESTE,SALVA_TESTE} from '../types';

const initialState = {
  teste: {},
  loading: true,
};

export default function (state = initialState, action) {
    switch (action.type) {
    case GET_TESTE:
      return {
        ...state,
        teste: action.payload,
        loading: false,
      };
      case SALVA_TESTE:
      return {
        ...state,
        teste: action.payload,
        loading: false,
      };
    default:
      return state;
  }
}

testeAction.js

import {GET_TESTE, TESTE_ERROR,SALVA_TESTE} from '../types';



export const getTeste = () => async dispatch => {
  try {
   var res = await localStorage.getItem("state").teste;
    dispatch ({
      type: GET_TESTE,
      payload: res,
    });
  } catch (e) {
    dispatch ({
      type: TESTE_ERROR,
      payload: console.log (e),
    });
    console.error (e);
    throw new Error (e);
  }
};

export const salvaTeste = (teste) => async dispatch => {
  try {
    console.log(teste)
    dispatch ({
      type: SALVA_TESTE,
      payload: teste,
    });
  } catch (e) {
    dispatch ({
      type: TESTE_ERROR,
      payload: console.log (e),
    });
    console.error (e);
    throw new Error (e);
  }
};

  • where to start your master component? it on it that should be done loading what is in localStorage is like this, in your code it seems that you do not have the Provider part so I can’t say.

  • is initializing in store.js with loadState()

  • I work with React never done so, I always do an event in the init of the main component where you saw this code? which already initial by this function?

  • I found on the net...?

  • Dispatch at the beginning of the component that appears first

  • you have example?

  • basically like this: function counterReducer(state = { value: 0 }, {type, payload}) { know that part of the Return then where is the object {value: 0} that’s where I do.

  • It should not put solved in the title because it corrupts the principle of the site. The way to indicate that it is resolved is to accept an answer as a solution by clicking on the right that appears to the left of it.

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.

  • but I explained and put code that I used in the test...what other information you speak?

Show 5 more comments

1 answer

2


createStore does not admit 4 arguments, but only 3.

  1. Reducer (Function)
  2. preloadedState (any)
  3. Engineering ()

I played an example here, changing just about that: loading the state from the localStorage and passing as the second argument.

Edit trusting-hermann-j2x7j

  • that same...it was only exchange initialstate by loadstate in createstore...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.