I'd like to dynamically append my empty array using useState. I want the program to work in such a way that on each button click, it fetches new data and appends it to the already existing array. How do I do this. The api I'm fetching automatically has new data upon refreshing the page.
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const[data, setData] = useState([]);
let info = [];
const handleFetch = () => {
fetch("https://www.randomuser.me/api")
.then((response) => response.json())
.then((data) => setData(data.results));
}
const information = data.map((details) => {
return (
<>
<h1> {details.name.title} </h1>
<h1> {details.name.first} </h1>
<h1> {details.name.last} </h1>
<img src = {details.picture.large}/>
</>
)
})
return (
<div className="App">
<button onClick = {handleFetch}>Fetch New Details</button>
<div>{information}</div>
</div>
);
}
CodePudding user response:
First, don't shadow the variable. Use a different variable name in your API response handler so you can access both. So instead of this:
.then((data) => setData(data.results));
Something like this:
.then((newData) => setData(newData.results));
Then you can merge the two arrays when setting state. For example, you can concat
the arrays:
setData(data.concat(newData.results))