Reputation:
I have a task to call an API, save the API data into local storage, and retrieve that same data when a page is reloaded.
However, the API gets called on every F5 and the data it contains gets randomized, (because API returns a bunch of random facts). So i have the Mount() and Update(), the data is in local storage, but i can't get it to stay and retrieve from there.
I've tried some if statements inside Mount(), for example to check length, and the like, but none worked. Help, I don't know what I'm doing wrong. This is the code:
import React from "react"
class LogicContainer extends React.Component {
constructor() {
super()
this.state = {
isLoading: true,
allFacts: []
}
)
}
//Call to API, get facts, put them into local storage.
componentDidMount() {
fetch("https://catfact.ninja/facts?limit=1000")
.then(response => response.json())
.then(response => {
const allFactsApi = response.data
this.setState({
isLoading: false,
allFacts: allFactsApi
})
localStorage.setItem("allFacts", JSON.stringify(allFactsApi))
})
console.log(this.state.allFacts.length)
}
/*check if facts have changed on reload and save them in tempFacts*/
componentDidUpdate(prevProps, prevState) {
if(prevState.allFacts !== this.state.allFacts) {
const tempFacts = JSON.stringify(this.state.allFacts)
localStorage.setItem("allFacts", tempFacts)
}
}
render() {
return(
<div></div>
)
}
}
export default LogicContainer;
Upvotes: 1
Views: 763
Reputation: 601
You are setting the data into the localStorage properly. But the problem is you are never actually retrieving it. You are just placing it in the state but the state will reset when the lifecycle of your component comes to an end (when F5 comes along for example). This is the code for retrieving data in localStorage:
localStorage.getItem("allFacts")
Bare in mind: When a user refreshes the website, the "componentDidUpdate" is not going to run, given that the page is actually reloading from scratch. What you should actually be doing is adding the snippet of code mentioned above on your "componentDidMount()" to check wether previous data exists in localStorage or if it should be retrieved from the API. If the data exists, then set the state to that. Otherwise, fetch the data from the API as you are doing now:
componentDidMount() {
// Check if localStorage has an assigned value for item "allFacts"
if(localStorage.getItem("allFacts")!== null){
// Set the state to that
this.setState({
isLoading: false,
allFacts: localStorage.getItem("allFacts")
})
// Otherwise, retrieve it from the API and set the state as well as the localStorage
}else{
fetch("https://catfact.ninja/facts?limit=1000")
.then(response => response.json())
.then(response => {
const allFactsApi = response.data
this.setState({
isLoading: false,
allFacts: allFactsApi
})
localStorage.setItem("allFacts", JSON.stringify(allFactsApi))
})
}
console.log(this.state.allFacts.length)
}
Upvotes: 1