twoam
twoam

Reputation: 892

Cant store data in setState react

First I check if Localstorage is supported, if it is I check if there is an item query in localstorage. If there is a item it should update to the query state. Before setState I have an alert and it alerts the item fine. But after the setState I alert again but it displays nothing? Somebody knows why? Even if I replace this.setState({query: localStorage.getItem("query")}) with this.setState({query: 'test'}) it doesnt display test in the alert?

getLocalStorage = () => {
    if (typeof(Storage) !== "undefined") {

        if (localStorage.getItem("query") !== null) {
            //Alerts 'a string'
            alert(localStorage.getItem("query"));

            this.setState({
                query: localStorage.getItem("query")
            });

            //Alerts nothing?
            alert(this.state.query);
            this.search();
        }
        else{
            this.getLocation();
        }
    }
    else {
        this.getLocation();
    }
};

Upvotes: 1

Views: 245

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58593

setState won't show direct change it will take time :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

If you want state value just after it's set you have to use it like this :

this.setState({
    query: localStorage.getItem("query")
},() => {
    alert(this.state.query);
});

For more details , please read setState

Upvotes: 5

Pankaj Bisht
Pankaj Bisht

Reputation: 994

setState is asynchronous method so that way you are geting this kind of response. So for this bug you can see -

Is there a synchronous alternative of setState() in Reactjs

Upvotes: 1

Related Questions