I've got this function that takes in a data set (JSON) and returns an object. But I want to be able to change this data set every 2 seconds. So I need to somehow change that argument every 2 seconds and then call it so a different object is rendered every two seconds
The Function:
const [dataset, setDataSet] = useState(season19) const stats = [{"stat" :"points" , ppg: ""}, {"stat": "rebounds", ast: ""}, {"stat": "assists", reb: ""}] const sortedData = (dataset, nums) => { const finalData = nums.map((stat) => { if(Object.values(stat).includes("points")){ return{ ...stat, ppg: dataset[0].pts } } else if(Object.values(stat).includes("rebounds")){ return{ ...stat, reb:dataset[0].reb } } else if(Object.values(stat).includes("assists")){ return{ ...stat, ast:dataset[0].ast } } }) return finalData }
and im calling it like so:
sortedData(dataset,stats)
The other two data sets are season20 and season21
How would I approach this?
What I tried
I put this into the sortedData function ,
setInterval(() => {
setDataset(season20)
}, 2000)
it works but obviously it only changes to season20, how can I do it so it changes to season21 also
You need use useEffect and put inside setInterval for every 2s state should be change. Component should be look about that. live code
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [season, setSeason] = useState("season19");
useEffect(() => {
const next = setInterval(() => {
let num = Number(season.substring(6, 9));
let str = `season${++num}`;
if (num > 25) return clearInterval(next); // remove setInterval after N-times
setSeason(str);
}, 2000);
return () => clearInterval(next); // remove setInterval after comp unmounted
}, [season]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>{season}</h2>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.