I want data state to be an array which adds up the data when the data in the API changes
such that it stores previous data as well as new data so I can map them and display them
App.js
import React, { useEffect, useState } from "react";
const App = () => {
const [data, setData] = useState([]);
const [entireData, setEntireDate] = useState([]);
let arr = [];
const fetchAPI = async () => {
const API = await fetch("https://randomuser.me/api");
const json = await API.json();
let results = json.results;
setData(results);
};
useEffect(() => {
fetchAPI();
}, []);
useEffect(() => {}, [data]);
return (
<>
<div className="container">
<p>
{data.map((val, idx, arr) => {
return val.login.username;
})}
</p>
<img
src={data.map((val, idx, arr) => {
return val.picture.large;
})}
alt="getPicFromJson"
/>
</div>
</>
);
};
export default App;
index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);
maybe try something like this
const fetchAPI = async () => {
const API = await fetch("https://randomuser.me/api");
const json = await API.json();
let results = json.results;
// here you get the old data and pushing the results into Data
Data.push(results)
// and setData to Data that has (Data + results)
setData(Data);
};
also if you want to have your data after refreshing your browser , you may need to store Data in localstorage and get the initial data from that