Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react load local storage at first

Tags:

reactjs

redux

I have a react app like where I have App.js which includes my Headers and Footers ..

In there I am storing my state to local storage.. After storing I can retrieve it ..

But I am having problem on loading it.. In my browser when I do localstorage['key'] it gives me the data but I am unable to load.

Where should I load it first ?

I have Root.js :

class Root extends Component {
  render() {
    const { store } = this.props
    return (
      <Provider store={store}>
          <ReduxRouter />
      </Provider>
    )
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired
}

export default Root

and index.js at outer level :

const store = configureStore()


render(

    <Root store={store} />,
  document.getElementById('root')
)

Where should I load my localStorage ?

Need help . I need to know what is called first in react so that I can make a call to load localStorage there .. If it is not bad idea

like image 657
varad Avatar asked Nov 09 '22 20:11

varad


1 Answers

You're using redux, so you should read the data as the result of an action.

The simplest way to make this work would be:

  1. Under ReduxRouter there should be a connected component. See docs
  2. In that connected component, add componentDidMount to call an action getStuffFromLocalstorage. See React lifecycle events
  3. In your reducer, get what you want from localStorage and populate the state

It might be an antipattern to do it in your reducer, but it will at least make the redux-flow go around.

like image 70
andersem Avatar answered Nov 14 '22 21:11

andersem