I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have
const [data, setData] = useState[]
useEffect(() => {
const fetchPrice = async () => {
const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h
const btcusd = data.data.results.map(
(d) => {
return {
open: d.open,
close: d.close,
low: d.low,
high: d.high,
time: toDateStamp(d.datetime),
};
}
);
setData(btcusd)
};
fetchPrice()
}, []);
The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?
Edit:
My bad guys, I have no issues to have the useffect runs again as i have another useeffect for that purpose whenever a user clicks on a new timeframe. My question is how can I store the chosen timeframes into a state and then re-use them again should the user chooses the timeframe that he chose before? This would be nice as I can stop outgoing network request.
CodePudding user response:
can use the spread operator inside setData()
to get the old values, then add the new value, something like this:
setData( oldValues => [ ...oldValues, newValue ] );
CodePudding user response:
You could set data as object with keys as timeframes f.e.
const [data, setData] = useState();
const TIMEFRAMES = {
HOUR: '1h',
HALF_HOUR: '30min',
};
const hourlyNewData = { price: 1 };
setData((prevdata) => {
...prevData,
[TIMEFRAMES.HOUR]: newData,
});
const minutelyNewData = { price: 1.1 };
setData((prevData) => {
...prevData,
[TIMEFRAMES.HALF_HOUR]: minutelyNewData,
});
// and to access data:
const hourlyData = data[TIMEFRAMES.HOUR];
const minutelyData = data[TIMEFRAMES.HALF_HOUR]
CodePudding user response:
You need to add your dynamic values, like 1h
and poolName
to the dependency array like this:
useEffect(() => {
...
}, [1h, poolNames])