So i have the following component
const ChartContainer: React.FC = () => {
const [data, setData] = React.useState<unknown>([])
const [prevMonthStamp, setPrevMonthStamp] = React.useState<number>()
React.useEffect(() => {
var d: any = new Date();
d.setMonth(d.getMonth() - 30);//timestamp of x months ago
d.setHours(0, 0, 0, 0);
setPrevMonthStamp((d / 1000 | 0) * 1000);
}, [])
React.useEffect(() => {
let url = binanceApi
let proxyUrl = corsProxy
axios({
method: 'get',
url: proxyUrl+url
}).then(res => {
if (prevMonthStamp) {
setData(res.data.filter((i: number[]) => i[0] >= prevMonthStamp))
}
}).catch(err => {
console.log(err)
})
}, [prevMonthStamp])
if (Array.isArray(data) && data?.length > 0) {
return (
<Canvas data={convertData(data)} />
);
} else {
return <Spinner />
}
}
And I notice that the api is being called twice
Supposedly on component mount, im setting prevMonthStamp, and once its set , the other useEffect is being used.
Why it happens to be used twice?
setPrevMonthStampin your firstuseEffectuseEffect()hook is called when the component is mounted. So, the seconduserEffect()is being executed once when the component is mounted, and second time when it's dependencyprevMountStampis set on the firstuseEffect()call.