My goal is to take the information from tempArr and set it as postData. If I don't use the if statement it keeps looping through all the data from the before mentioned array. While the tempArr contains all the necessary information from DB, I think that the problem lies in the useEffect hook because as far as I understand it just doesn't loop through it the second time. Sadly I have no idea how to fix it. A picture from console is provided to better understand the problem.
const [postData, setPost] = useState([])
const axios = require('axios');
let done = false;
let tempArr = []
useEffect(() => {
axiosPull()
console.log(done, "before the if statement")
if(done){
console.log("inside the IF statement")
{setPost(tempArr)}
done = false
}
})
const axiosPull = () => {
const url = 'http://localhost/.../api/product/bookRead'
const url2 = 'http://localhost/.../api/product/furnitureRead'
const url3 = 'http://localhost/.../api/product/dvdRead'
axios.get(url).then(response => response.data)
.then((data) => {
data.data.map(data =>{
tempArr.push(data)
})
})
axios.get(url2).then(response => response.data)
.then((data) => {
data.data.map(data =>{
tempArr.push(data)
})
})
axios.get(url3).then(response => response.data)
.then((data) => {
data.data.map(data =>{
tempArr.push(data)
})
console.log(tempArr)
done = true
console.log(done)
})
};
return (
<div>
<div className="productContainer">
<Post posts={postData} />
</div>
</div>
)
You should probably have an empty dependency array in that useEffect to prevent it running on each render.
useEffect(() => {
axiosPull();
}, []);
You can a) shorten your code, b) remove the dependence of a local component variable (tmpArr), and c) set state within the axiosPull function itself.
function axiosPull() {
const url = 'http://localhost/.../api/product/bookRead'
const url2 = 'http://localhost/.../api/product/furnitureRead'
const url3 = 'http://localhost/.../api/product/dvdRead';
// Group the urls in an array
const urls = [url1, url2, url3];
// Create an array of promises
const promises = urls.map(url => {
return axios.get(url);
});
// Wait til they either resolve/reject
Promise.all(promises).then(responses => {
// Then `map` over the responses of each
// resolved promise and return the data you were
// adding to `tempArr`. You may need `flatMap` here
// instead of `map` depending on your use-case
const mapped = responses.map(data => {
return data.data;
});
// And then set the state with that data
setPost(mapped);
});
};