Qiang Yao
Qiang Yao

Reputation: 185

How to keep the data in localStorage after refreshing?

I am using react to write a Child component. This child component gets its states from its Parent component.

Class ChildDetails extends Component{
    constructor(props) {
        super(props);
        this.state = {
          messageId: this.props.messageId,
        };
    }
    componentDidMount() {
        localStorage.setItem("messageId", this.props.messageId);
    }
}

I am sure that when the Child component is rendered at first, the data is stored into the localStorage. But when I want to get the data from localStorage after refreshing the page, the localStorage is cleared. I think it may be because I am using a local development environment, I use

localhost:3000

to access my application. But I don't know why.

My Parent component is the root App, I use Route to pass the data to the Child component. The data is from the redux store.

<Route
    path="/messageDetails"
    render={(props) => (
    <Child
     {...props}
     messageId={this.props.messageId}
     />
  )}
></Route>

const mapStateToProps = (state) => {
    messageId: state.Reducer.messageId,
}

Upvotes: 1

Views: 758

Answers (1)

Hyetigran
Hyetigran

Reputation: 1215

When you refresh your browser, your components will re-render and call the componentDidMount lifecycle method. So I think the error might come from the fact that your messageId might be undefined. One way to avoid this is to add a conditional so that if you have a an item in localStorage, it won't try to set it.

Class ChildDetails extends Component{
    constructor(props) {
        super(props);
        this.state = {
          messageId: this.props.messageId,
        };
    }
    componentDidMount() {
        if(!localStorage.getItem("messageId")){
            localStorage.setItem("messageId", this.props.messageId);
        }
    }
}

As an aside, I would advise against saving messageId into ChildDetails state as the intention of redux is to place state in a central location and feed it into components as necessary.

Upvotes: 1

Related Questions