Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  54] [ 2]  / answers: 1 / hits: 53947  / 5 Years ago, wed, april 10, 2019, 12:00:00

I have a react-big-calendar, I want to fetch the events of this week from the backend and the other weeks from the local storage.



My code is :



componentDidMount() {
fetch(url)
.then(Response => Response.json())
.then(data => {
let evts = data;
for (let i = 0; i < evts.length; i++) {
evts[i].start = moment(evts[i].start).toDate();
evts[i].end = moment(evts[i].end).toDate();
this.state.evt1.push(evts[i])
}
this.setState({
evt1: evts,
prevEvents : evts
})
})
console.log(this.state.evt1)
const cachedHits = JSON.parse(localStorage.getItem('Evènements'))
console.log(cachedHits)
for (let j = 0; j <cachedHits.length; j++) {
cachedHits[j].start = moment(cachedHits[j].start).toDate();
cachedHits[j].end = moment(cachedHits[j].end).toDate();
this.state.evt2.push(cachedHits[j])
}
this.setState( {
evt2: this.state.evt2
})
this.setState({
events: [...this.state.evt1, ...this.state.evt2]
})
console.log(this.state.events)
}


the events is the merged array of evt1 (events from the backend) and evt2 (events from the localstorage), when I run it, I get on my console :



The evt1 are :



enter



The evt2 are :



enter



But, on my calendar, just the evt2 are displayed and not all the events (evt1 and evt2).



How can display all the events on my calendar ?


More From » arrays

 Answers
1

Because you are making an HTTP call to your server, it takes some time to fetch the data. Instead of setting events state directly, you should wait for the response of your HTTP call. Your code should be like this:



componentDidMount() {
fetch(url)
.then(Response => Response.json())
.then(data => {
let evts = data;
for (let i = 0; i < evts.length; i++) {
evts[i].start = moment(evts[i].start).toDate();
evts[i].end = moment(evts[i].end).toDate();
this.state.evt1.push(evts[i])
}
this.setState({
evt1: evts,
prevEvents: evts
})
})
.then(() => {

console.log(this.state.evt1)
const cachedHits = JSON.parse(localStorage.getItem('Evènements'))
console.log(cachedHits)
for (let j = 0; j < cachedHits.length; j++) {
cachedHits[j].start = moment(cachedHits[j].start).toDate();
cachedHits[j].end = moment(cachedHits[j].end).toDate();
this.state.evt2.push(cachedHits[j])
}
this.setState({
evt2: this.state.evt2
})
this.setState({
events: [...this.state.evt1, ...this.state.evt2]
})
console.log(this.state.events)

});
}


I also recommend you to have a catch block in your promise chain to handle errors.


[#52272] Friday, April 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
;