'Variables updated in fetch method don't retain in state
const searchCacheFlightHotelsPackage = () => {
setValues({ ...values, loading: true });
let result = null;
getCacheFlightHotelsPackage() //returns a promise
.then((data) => {
if (data.list.length > 0) {
result = paginate(data.list);
hotelFlightPackageList = data.list;
} else {
console.log("sorry no packages found========");
}
console.log(hotelFlightPackageList);
setValues({ ...values, loading: false });
})
.catch((e) => {
console.log("packages data error=======", e);
setValues({ ...values, loading: false });
});
I have variables outside this function like let hotelFlightPackageList = []; which updates in the method but once outside the method it's back to being an empty array. I have also tried using setValues which you can see an example of with the loading setting to false. I wish I could just update the global state in fetch but It gives a react hook error when doing that.
Solution 1:[1]
Turns out you can update the global state in fetch once you make the global state variable a const outside of the fetch! Working now!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexander Bishop |
