Can't set state after saving it to local storage in React












0















I am implementing a search filter in my app and need to persist data between browser refreshes.



Here is my code:



    class App extends Component {
state = {
data: shop,
direction: {
price: "asc",
title: "asc"
},
searchTitle: "",
searchPrice: {
min: null,
max: null
}
};

componentDidUpdate() {
const state = {
searchTitle: this.state.searchTitle,
searchPrice: this.state.searchPrice,
direction: this.state.direction
};

window.localStorage.setItem("saved_state", JSON.stringify(state));
}

componentDidMount() {
const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}
}

// PRICE SORT
priceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// OLD PRICE SORT
oldPriceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE SORT
titleSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => a.data[key].localeCompare(b.data[key])
: (a, b) => b.data[key].localeCompare(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE FILTER
updateTitleSearch = event => {
this.setState({
searchTitle: event.target.value
});
this.titleSearch();
};

titleSearch = () => {
if (this.state.searchTitle) {
this.setState({
data: shop
.filter(item => {
return (
item.data.title
.toLowerCase()
.indexOf(this.state.searchTitle.toLowerCase()) !== -1
);
})
.sort(
this.state.direction.title === "asc"
? (a, b) => a.data.title.localeCompare(b.data.title)
: (a, b) => b.data.title.localeCompare(a.data.title)
)
});
}
};

// PRICE FILTER
updateMinSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, min: event.target.value }
});
};

updateMaxSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, max: event.target.value }
});
};

priceSearch = () => {
if (this.state.searchPrice.min || this.state.searchPrice.max) {
this.setState({
data: shop
.filter(item => {
return (
parseFloat(item.data.price) >= this.state.searchPrice.min &&
parseFloat(item.data.price) <= this.state.searchPrice.max
);
})
.sort(
this.state.direction.price === "asc"
? (a, b) => parseFloat(a.data.price) - parseFloat(b.data.price)
: (a, b) => parseFloat(b.data.price) - parseFloat(a.data.price)
)
});
}

if (!this.state.searchPrice.max) {
this.setState({
data: shop.filter(item => {
return parseFloat(item.data.price) >= this.state.searchPrice.min;
})
});
}
};

render() {
return (
<div className="page-container">
<h1>Welcome to ShopMeNow!</h1>
<Filters
updateTitleSearch={this.updateTitleSearch}
titleSearch={this.titleSearch}
updateMinSearchPrice={this.updateMinSearchPrice}
updateMaxSearchPrice={this.updateMaxSearchPrice}
priceSearch={this.priceSearch}
/>
<ItemTable
data={this.state.data}
priceSort={this.priceSort}
oldPriceSort={this.oldPriceSort}
titleSort={this.titleSort}
/>
</div>
);
}
}

export default App;


My aim is to fetch the saved data in the componentDidMount() hook. But it doesn't seem to work (i've already tried to console.log it)



What do I have to do in order to get it going? Thank you community!










share|improve this question




















  • 1





    What you mean by "doesn't seems to work"?

    – keul
    Nov 16 '18 at 9:28











  • I mean it doesn't work.

    – doglabel
    Nov 16 '18 at 9:29








  • 1





    Could you include your entire component, so we can see how you are updating your state etc.?

    – Tholle
    Nov 16 '18 at 9:30











  • Just updated the code.

    – doglabel
    Nov 16 '18 at 9:32











  • I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

    – keul
    Nov 16 '18 at 11:18
















0















I am implementing a search filter in my app and need to persist data between browser refreshes.



Here is my code:



    class App extends Component {
state = {
data: shop,
direction: {
price: "asc",
title: "asc"
},
searchTitle: "",
searchPrice: {
min: null,
max: null
}
};

componentDidUpdate() {
const state = {
searchTitle: this.state.searchTitle,
searchPrice: this.state.searchPrice,
direction: this.state.direction
};

window.localStorage.setItem("saved_state", JSON.stringify(state));
}

componentDidMount() {
const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}
}

// PRICE SORT
priceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// OLD PRICE SORT
oldPriceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE SORT
titleSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => a.data[key].localeCompare(b.data[key])
: (a, b) => b.data[key].localeCompare(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE FILTER
updateTitleSearch = event => {
this.setState({
searchTitle: event.target.value
});
this.titleSearch();
};

titleSearch = () => {
if (this.state.searchTitle) {
this.setState({
data: shop
.filter(item => {
return (
item.data.title
.toLowerCase()
.indexOf(this.state.searchTitle.toLowerCase()) !== -1
);
})
.sort(
this.state.direction.title === "asc"
? (a, b) => a.data.title.localeCompare(b.data.title)
: (a, b) => b.data.title.localeCompare(a.data.title)
)
});
}
};

// PRICE FILTER
updateMinSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, min: event.target.value }
});
};

updateMaxSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, max: event.target.value }
});
};

priceSearch = () => {
if (this.state.searchPrice.min || this.state.searchPrice.max) {
this.setState({
data: shop
.filter(item => {
return (
parseFloat(item.data.price) >= this.state.searchPrice.min &&
parseFloat(item.data.price) <= this.state.searchPrice.max
);
})
.sort(
this.state.direction.price === "asc"
? (a, b) => parseFloat(a.data.price) - parseFloat(b.data.price)
: (a, b) => parseFloat(b.data.price) - parseFloat(a.data.price)
)
});
}

if (!this.state.searchPrice.max) {
this.setState({
data: shop.filter(item => {
return parseFloat(item.data.price) >= this.state.searchPrice.min;
})
});
}
};

render() {
return (
<div className="page-container">
<h1>Welcome to ShopMeNow!</h1>
<Filters
updateTitleSearch={this.updateTitleSearch}
titleSearch={this.titleSearch}
updateMinSearchPrice={this.updateMinSearchPrice}
updateMaxSearchPrice={this.updateMaxSearchPrice}
priceSearch={this.priceSearch}
/>
<ItemTable
data={this.state.data}
priceSort={this.priceSort}
oldPriceSort={this.oldPriceSort}
titleSort={this.titleSort}
/>
</div>
);
}
}

export default App;


My aim is to fetch the saved data in the componentDidMount() hook. But it doesn't seem to work (i've already tried to console.log it)



What do I have to do in order to get it going? Thank you community!










share|improve this question




















  • 1





    What you mean by "doesn't seems to work"?

    – keul
    Nov 16 '18 at 9:28











  • I mean it doesn't work.

    – doglabel
    Nov 16 '18 at 9:29








  • 1





    Could you include your entire component, so we can see how you are updating your state etc.?

    – Tholle
    Nov 16 '18 at 9:30











  • Just updated the code.

    – doglabel
    Nov 16 '18 at 9:32











  • I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

    – keul
    Nov 16 '18 at 11:18














0












0








0








I am implementing a search filter in my app and need to persist data between browser refreshes.



Here is my code:



    class App extends Component {
state = {
data: shop,
direction: {
price: "asc",
title: "asc"
},
searchTitle: "",
searchPrice: {
min: null,
max: null
}
};

componentDidUpdate() {
const state = {
searchTitle: this.state.searchTitle,
searchPrice: this.state.searchPrice,
direction: this.state.direction
};

window.localStorage.setItem("saved_state", JSON.stringify(state));
}

componentDidMount() {
const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}
}

// PRICE SORT
priceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// OLD PRICE SORT
oldPriceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE SORT
titleSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => a.data[key].localeCompare(b.data[key])
: (a, b) => b.data[key].localeCompare(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE FILTER
updateTitleSearch = event => {
this.setState({
searchTitle: event.target.value
});
this.titleSearch();
};

titleSearch = () => {
if (this.state.searchTitle) {
this.setState({
data: shop
.filter(item => {
return (
item.data.title
.toLowerCase()
.indexOf(this.state.searchTitle.toLowerCase()) !== -1
);
})
.sort(
this.state.direction.title === "asc"
? (a, b) => a.data.title.localeCompare(b.data.title)
: (a, b) => b.data.title.localeCompare(a.data.title)
)
});
}
};

// PRICE FILTER
updateMinSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, min: event.target.value }
});
};

updateMaxSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, max: event.target.value }
});
};

priceSearch = () => {
if (this.state.searchPrice.min || this.state.searchPrice.max) {
this.setState({
data: shop
.filter(item => {
return (
parseFloat(item.data.price) >= this.state.searchPrice.min &&
parseFloat(item.data.price) <= this.state.searchPrice.max
);
})
.sort(
this.state.direction.price === "asc"
? (a, b) => parseFloat(a.data.price) - parseFloat(b.data.price)
: (a, b) => parseFloat(b.data.price) - parseFloat(a.data.price)
)
});
}

if (!this.state.searchPrice.max) {
this.setState({
data: shop.filter(item => {
return parseFloat(item.data.price) >= this.state.searchPrice.min;
})
});
}
};

render() {
return (
<div className="page-container">
<h1>Welcome to ShopMeNow!</h1>
<Filters
updateTitleSearch={this.updateTitleSearch}
titleSearch={this.titleSearch}
updateMinSearchPrice={this.updateMinSearchPrice}
updateMaxSearchPrice={this.updateMaxSearchPrice}
priceSearch={this.priceSearch}
/>
<ItemTable
data={this.state.data}
priceSort={this.priceSort}
oldPriceSort={this.oldPriceSort}
titleSort={this.titleSort}
/>
</div>
);
}
}

export default App;


My aim is to fetch the saved data in the componentDidMount() hook. But it doesn't seem to work (i've already tried to console.log it)



What do I have to do in order to get it going? Thank you community!










share|improve this question
















I am implementing a search filter in my app and need to persist data between browser refreshes.



Here is my code:



    class App extends Component {
state = {
data: shop,
direction: {
price: "asc",
title: "asc"
},
searchTitle: "",
searchPrice: {
min: null,
max: null
}
};

componentDidUpdate() {
const state = {
searchTitle: this.state.searchTitle,
searchPrice: this.state.searchPrice,
direction: this.state.direction
};

window.localStorage.setItem("saved_state", JSON.stringify(state));
}

componentDidMount() {
const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}
}

// PRICE SORT
priceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// OLD PRICE SORT
oldPriceSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => parseFloat(a.data[key]) - parseFloat(b.data[key])
: (a, b) => parseFloat(b.data[key]) - parseFloat(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE SORT
titleSort = key => {
this.setState({
data: shop.sort(
this.state.direction[key] === "asc"
? (a, b) => a.data[key].localeCompare(b.data[key])
: (a, b) => b.data[key].localeCompare(a.data[key])
),
direction: {
[key]: this.state.direction[key] === "asc" ? "desc" : "asc"
}
});
};

// TITLE FILTER
updateTitleSearch = event => {
this.setState({
searchTitle: event.target.value
});
this.titleSearch();
};

titleSearch = () => {
if (this.state.searchTitle) {
this.setState({
data: shop
.filter(item => {
return (
item.data.title
.toLowerCase()
.indexOf(this.state.searchTitle.toLowerCase()) !== -1
);
})
.sort(
this.state.direction.title === "asc"
? (a, b) => a.data.title.localeCompare(b.data.title)
: (a, b) => b.data.title.localeCompare(a.data.title)
)
});
}
};

// PRICE FILTER
updateMinSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, min: event.target.value }
});
};

updateMaxSearchPrice = event => {
this.setState({
searchPrice: { ...this.state.searchPrice, max: event.target.value }
});
};

priceSearch = () => {
if (this.state.searchPrice.min || this.state.searchPrice.max) {
this.setState({
data: shop
.filter(item => {
return (
parseFloat(item.data.price) >= this.state.searchPrice.min &&
parseFloat(item.data.price) <= this.state.searchPrice.max
);
})
.sort(
this.state.direction.price === "asc"
? (a, b) => parseFloat(a.data.price) - parseFloat(b.data.price)
: (a, b) => parseFloat(b.data.price) - parseFloat(a.data.price)
)
});
}

if (!this.state.searchPrice.max) {
this.setState({
data: shop.filter(item => {
return parseFloat(item.data.price) >= this.state.searchPrice.min;
})
});
}
};

render() {
return (
<div className="page-container">
<h1>Welcome to ShopMeNow!</h1>
<Filters
updateTitleSearch={this.updateTitleSearch}
titleSearch={this.titleSearch}
updateMinSearchPrice={this.updateMinSearchPrice}
updateMaxSearchPrice={this.updateMaxSearchPrice}
priceSearch={this.priceSearch}
/>
<ItemTable
data={this.state.data}
priceSort={this.priceSort}
oldPriceSort={this.oldPriceSort}
titleSort={this.titleSort}
/>
</div>
);
}
}

export default App;


My aim is to fetch the saved data in the componentDidMount() hook. But it doesn't seem to work (i've already tried to console.log it)



What do I have to do in order to get it going? Thank you community!







javascript reactjs local-storage






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 9:32







doglabel

















asked Nov 16 '18 at 9:26









doglabeldoglabel

206




206








  • 1





    What you mean by "doesn't seems to work"?

    – keul
    Nov 16 '18 at 9:28











  • I mean it doesn't work.

    – doglabel
    Nov 16 '18 at 9:29








  • 1





    Could you include your entire component, so we can see how you are updating your state etc.?

    – Tholle
    Nov 16 '18 at 9:30











  • Just updated the code.

    – doglabel
    Nov 16 '18 at 9:32











  • I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

    – keul
    Nov 16 '18 at 11:18














  • 1





    What you mean by "doesn't seems to work"?

    – keul
    Nov 16 '18 at 9:28











  • I mean it doesn't work.

    – doglabel
    Nov 16 '18 at 9:29








  • 1





    Could you include your entire component, so we can see how you are updating your state etc.?

    – Tholle
    Nov 16 '18 at 9:30











  • Just updated the code.

    – doglabel
    Nov 16 '18 at 9:32











  • I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

    – keul
    Nov 16 '18 at 11:18








1




1





What you mean by "doesn't seems to work"?

– keul
Nov 16 '18 at 9:28





What you mean by "doesn't seems to work"?

– keul
Nov 16 '18 at 9:28













I mean it doesn't work.

– doglabel
Nov 16 '18 at 9:29







I mean it doesn't work.

– doglabel
Nov 16 '18 at 9:29






1




1





Could you include your entire component, so we can see how you are updating your state etc.?

– Tholle
Nov 16 '18 at 9:30





Could you include your entire component, so we can see how you are updating your state etc.?

– Tholle
Nov 16 '18 at 9:30













Just updated the code.

– doglabel
Nov 16 '18 at 9:32





Just updated the code.

– doglabel
Nov 16 '18 at 9:32













I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

– keul
Nov 16 '18 at 11:18





I'm sorry but replying just saying "it doesn work" means nothing for us to help you. It's not updating your component as expected? Do you get a traceback error?

– keul
Nov 16 '18 at 11:18












3 Answers
3






active

oldest

votes


















0














instead of setting State in ComponentDidMount , why dont you create a entire different function and then call that function in ComponentDidMount.



All the Code of Setting State add in that function.
Try this and let me know if it works , Cheers !



    ComponentDidMount(){ 

this.changeValues();

}

changeValues(){

const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}

}





share|improve this answer
























  • Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

    – doglabel
    Nov 16 '18 at 10:17











  • you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

    – codemt
    Nov 16 '18 at 10:51











  • I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

    – doglabel
    Nov 16 '18 at 11:02



















0














The issue I think is you are saving data in localStorage inside componentDidUpdate and you are trying to get the data from local storage in componentDidMount.



You need to understand that componentDidMount called before componentDidUpdate which means you are reading the data from local storage before you set.



So you need to first set the data and then read data






share|improve this answer
























  • Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

    – doglabel
    Nov 16 '18 at 11:43











  • It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

    – doglabel
    Nov 16 '18 at 12:14



















0














Is there a particular reason why you're doing it in componentDidUpdate? If not, I would suggest moving that functionality to a separate function. The way things stand now, any update, including this.setStates on data, which you don't want to save to localStorage.



Perhaps you might consider writing a function that sets state and saves to localStorage, seeing as how your sort functions are already quite bulky.



Sample pseudocode:



setStateWithLocalStorage = newState => {
const { searchTitle, searchPrice, direction } = this.state;
this.setState(newState, () => {
localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
})
}


then you can use this function instead of this.setState on your sort functions.






share|improve this answer
























  • Wow! Thanks a lot. Gonna check it out and report the results.

    – doglabel
    Nov 17 '18 at 17:50












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334878%2fcant-set-state-after-saving-it-to-local-storage-in-react%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














instead of setting State in ComponentDidMount , why dont you create a entire different function and then call that function in ComponentDidMount.



All the Code of Setting State add in that function.
Try this and let me know if it works , Cheers !



    ComponentDidMount(){ 

this.changeValues();

}

changeValues(){

const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}

}





share|improve this answer
























  • Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

    – doglabel
    Nov 16 '18 at 10:17











  • you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

    – codemt
    Nov 16 '18 at 10:51











  • I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

    – doglabel
    Nov 16 '18 at 11:02
















0














instead of setting State in ComponentDidMount , why dont you create a entire different function and then call that function in ComponentDidMount.



All the Code of Setting State add in that function.
Try this and let me know if it works , Cheers !



    ComponentDidMount(){ 

this.changeValues();

}

changeValues(){

const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}

}





share|improve this answer
























  • Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

    – doglabel
    Nov 16 '18 at 10:17











  • you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

    – codemt
    Nov 16 '18 at 10:51











  • I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

    – doglabel
    Nov 16 '18 at 11:02














0












0








0







instead of setting State in ComponentDidMount , why dont you create a entire different function and then call that function in ComponentDidMount.



All the Code of Setting State add in that function.
Try this and let me know if it works , Cheers !



    ComponentDidMount(){ 

this.changeValues();

}

changeValues(){

const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}

}





share|improve this answer













instead of setting State in ComponentDidMount , why dont you create a entire different function and then call that function in ComponentDidMount.



All the Code of Setting State add in that function.
Try this and let me know if it works , Cheers !



    ComponentDidMount(){ 

this.changeValues();

}

changeValues(){

const state = JSON.parse(window.localStorage.getItem("saved_state"));

console.log(state);

if (state) {
this.setState({
searchTitle: state.searchTitle,
searchPrice: state.searchPrice,
direction: state.direction
});
}

}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 10:02









codemtcodemt

74113




74113













  • Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

    – doglabel
    Nov 16 '18 at 10:17











  • you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

    – codemt
    Nov 16 '18 at 10:51











  • I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

    – doglabel
    Nov 16 '18 at 11:02



















  • Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

    – doglabel
    Nov 16 '18 at 10:17











  • you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

    – codemt
    Nov 16 '18 at 10:51











  • I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

    – doglabel
    Nov 16 '18 at 11:02

















Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

– doglabel
Nov 16 '18 at 10:17





Hi! No it doesn't work. The console.log, though, shows me that localStorage works well and everything is being saved to my state. What the heck is wrong?

– doglabel
Nov 16 '18 at 10:17













you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

– codemt
Nov 16 '18 at 10:51





you don't have a constructor and you are also not using bind this.<methodname>.bind(this) - check this example [link] (codepen.io/gaearon/pen/xEmzGg?editors=0010) , it might help.

– codemt
Nov 16 '18 at 10:51













I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

– doglabel
Nov 16 '18 at 11:02





I'm using arrow functions which is the same. That's not where the problem lies. The console.log messages show me that the state changes. But somehow the filters don't work.

– doglabel
Nov 16 '18 at 11:02













0














The issue I think is you are saving data in localStorage inside componentDidUpdate and you are trying to get the data from local storage in componentDidMount.



You need to understand that componentDidMount called before componentDidUpdate which means you are reading the data from local storage before you set.



So you need to first set the data and then read data






share|improve this answer
























  • Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

    – doglabel
    Nov 16 '18 at 11:43











  • It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

    – doglabel
    Nov 16 '18 at 12:14
















0














The issue I think is you are saving data in localStorage inside componentDidUpdate and you are trying to get the data from local storage in componentDidMount.



You need to understand that componentDidMount called before componentDidUpdate which means you are reading the data from local storage before you set.



So you need to first set the data and then read data






share|improve this answer
























  • Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

    – doglabel
    Nov 16 '18 at 11:43











  • It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

    – doglabel
    Nov 16 '18 at 12:14














0












0








0







The issue I think is you are saving data in localStorage inside componentDidUpdate and you are trying to get the data from local storage in componentDidMount.



You need to understand that componentDidMount called before componentDidUpdate which means you are reading the data from local storage before you set.



So you need to first set the data and then read data






share|improve this answer













The issue I think is you are saving data in localStorage inside componentDidUpdate and you are trying to get the data from local storage in componentDidMount.



You need to understand that componentDidMount called before componentDidUpdate which means you are reading the data from local storage before you set.



So you need to first set the data and then read data







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 11:23









Hemadri DasariHemadri Dasari

10.2k32152




10.2k32152













  • Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

    – doglabel
    Nov 16 '18 at 11:43











  • It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

    – doglabel
    Nov 16 '18 at 12:14



















  • Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

    – doglabel
    Nov 16 '18 at 11:43











  • It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

    – doglabel
    Nov 16 '18 at 12:14

















Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

– doglabel
Nov 16 '18 at 11:43





Do you mean I should swap the code of componentDidMount and componentDidUpdate? I tried it but the app crashes.

– doglabel
Nov 16 '18 at 11:43













It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

– doglabel
Nov 16 '18 at 12:14





It makes sense though... Guess I'm gonna go down the path you've offered... Gonna report about the results here. Thanks my man!

– doglabel
Nov 16 '18 at 12:14











0














Is there a particular reason why you're doing it in componentDidUpdate? If not, I would suggest moving that functionality to a separate function. The way things stand now, any update, including this.setStates on data, which you don't want to save to localStorage.



Perhaps you might consider writing a function that sets state and saves to localStorage, seeing as how your sort functions are already quite bulky.



Sample pseudocode:



setStateWithLocalStorage = newState => {
const { searchTitle, searchPrice, direction } = this.state;
this.setState(newState, () => {
localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
})
}


then you can use this function instead of this.setState on your sort functions.






share|improve this answer
























  • Wow! Thanks a lot. Gonna check it out and report the results.

    – doglabel
    Nov 17 '18 at 17:50
















0














Is there a particular reason why you're doing it in componentDidUpdate? If not, I would suggest moving that functionality to a separate function. The way things stand now, any update, including this.setStates on data, which you don't want to save to localStorage.



Perhaps you might consider writing a function that sets state and saves to localStorage, seeing as how your sort functions are already quite bulky.



Sample pseudocode:



setStateWithLocalStorage = newState => {
const { searchTitle, searchPrice, direction } = this.state;
this.setState(newState, () => {
localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
})
}


then you can use this function instead of this.setState on your sort functions.






share|improve this answer
























  • Wow! Thanks a lot. Gonna check it out and report the results.

    – doglabel
    Nov 17 '18 at 17:50














0












0








0







Is there a particular reason why you're doing it in componentDidUpdate? If not, I would suggest moving that functionality to a separate function. The way things stand now, any update, including this.setStates on data, which you don't want to save to localStorage.



Perhaps you might consider writing a function that sets state and saves to localStorage, seeing as how your sort functions are already quite bulky.



Sample pseudocode:



setStateWithLocalStorage = newState => {
const { searchTitle, searchPrice, direction } = this.state;
this.setState(newState, () => {
localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
})
}


then you can use this function instead of this.setState on your sort functions.






share|improve this answer













Is there a particular reason why you're doing it in componentDidUpdate? If not, I would suggest moving that functionality to a separate function. The way things stand now, any update, including this.setStates on data, which you don't want to save to localStorage.



Perhaps you might consider writing a function that sets state and saves to localStorage, seeing as how your sort functions are already quite bulky.



Sample pseudocode:



setStateWithLocalStorage = newState => {
const { searchTitle, searchPrice, direction } = this.state;
this.setState(newState, () => {
localStorage.setItem('saved_state', { searchTitle, searchPrice, direction })
})
}


then you can use this function instead of this.setState on your sort functions.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 20:28









Jasper OngJasper Ong

11




11













  • Wow! Thanks a lot. Gonna check it out and report the results.

    – doglabel
    Nov 17 '18 at 17:50



















  • Wow! Thanks a lot. Gonna check it out and report the results.

    – doglabel
    Nov 17 '18 at 17:50

















Wow! Thanks a lot. Gonna check it out and report the results.

– doglabel
Nov 17 '18 at 17:50





Wow! Thanks a lot. Gonna check it out and report the results.

– doglabel
Nov 17 '18 at 17:50


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334878%2fcant-set-state-after-saving-it-to-local-storage-in-react%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine