I am trying to loop a fetch request based on a array with forEach. How do I store the data in a single array to later render it in JSX?
This is my beginner’s code so far.
import "./App.css";
function Temp2() {
var payloadArray = [9837, 5021, 0162, 7553];
let final = [];
let fetchNewArray = function () {
payloadArray.forEach((payload) => {
final.push(
fetch("API URL", {
payload,
})
.then((res) => res.json())
.then((json) => {
let q = json.data.toString(); // q = '1324646'
return q;
})
);
});
return Promise.all(final);
};
console.log(final); // was expecting final = ["q value 1", "q value 2" ,"q value 3"]
return (
<div>
<header className="App-header">
<button onClick={fetchNewArray}>GET VALUES</button>
{final.map((e, i) => {
return <p key={i}>{e}</p>;
})}
</header>
</div>
);
}
export default Temp2;
I would appreciate any help
>Solution :
You should call the fetchNewArray using a useEffect when the component load and set the values from Promise.all in a state variable:
function Temp2() {
const [values, setValues] = useState([]);
var payloadArray = [9837, 5021, 0162, 7553];
let fetchNewArray = function () {
const promises = [];
payloadArray.forEach((payload) => {
promises.push(
fetch('API URL', {
payload,
})
.then((res) => res.json())
.then((json) => {
let q = json.data.toString(); // q = '1324646'
return q;
})
);
});
Promise.all(promises).then((v) => setValues(v));
};
useEffect(() => {
fetchNewArray();
}, []);
return (
<div>
<header className='App-header'>
<button onClick={fetchNewArray}>GET VALUES</button>
{values.length ? (
values.map((e, i) => {
return <p key={i}>{e}</p>;
})
) : (
<>Loading...</>
)}
</header>
</div>
);
}
export default Temp2;