Query is getting called automatically after it gets resolved #5526
-
Hi Folks, I was trying to load data for rendering charts in my React app. I have a query which fetches data for the chart. const fetchCpuUsage = async (visionSystemId, startTime, endTime) => {
const url = `...`;
const response = await api.get(url);
return response.data;
};
export const useCPUUsage = ({ visionSystemId, startTime, endTime, timeRange }, config) => {
const { data, ...rest } = useQuery({
queryKey: ['cpu-usage', visionSystemId, startTime, endTime, timeRange],
queryFn: () => fetchCpuUsage(visionSystemId, startTime, endTime),
...config
});
return { data: data?.data, ...rest };
}; This is my component in which I'm calling the query and rendering a chart. import { memo } from 'react';
import dayjs from 'dayjs';
import { Row, Spin } from 'antd';
import { CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis } from 'recharts';
import { lineColors, useCPUUsage } from '~/features/monitoring';
import EmptyView from '~/components/EmptyView';
import { EMPTY_DATA_MESSAGE } from '~/constants';
const renderLinesForCPUCores = (data) => {
const { published_at, ...cores } = data[0];
const keys = Object.keys(cores || {});
return (
<>
{keys.map((key) => (
<Line key={key} type="monotone" dataKey={key} stroke={lineColors.cpuUsage[key]} activeDot={{ r: 8 }} />
))}
</>
)
}
// I call the below component in a parent component where I render 5 charts in that passing ` selectedVisionSystemId, selectedTimeRange` as props.
export const CPUChart = memo(({ selectedVisionSystemId, selectedTimeRange }) => {
const { data: cpuUsageData, isFetching: isFetchingCpuUsage } = useCPUUsage(
{
visionSystemId: selectedVisionSystemId,
startTime: '1682965800',
endTime: dayjs().unix(),
timeRange: selectedTimeRange
},
{ enabled: !!selectedTimeRange }
);
const transformedData = cpuUsageData?.map((item) => {
return {
...item,
published_at: dayjs(item.published_at * 1000).format('lll')
};
});
return (
<Spin spinning={isFetchingCpuUsage}>
{cpuUsageData?.length > 0 ? (
<LineChart
width={transformedData?.length * 24}
height={600}
data={transformedData}
margin={{
top: 20,
right: 30,
left: 20,
bottom: 5
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="published_at" allowDataOverflow minTickGap={16} />
<YAxis domain={[0, 100]} />
<Tooltip />
<Legend />
{renderLinesForCPUCores(transformedData)}
</LineChart>
) : (
<Row align="center">
<EmptyView message={EMPTY_DATA_MESSAGE} />
</Row>
)}
</Spin>
);
}); The query is getting called automatically after it is resolved. I also render 2 more charts and those are working fine. Here is the short video of how it is getting called. react-query-autocalling.mp4A bunch of calls named Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
@TkDodo, please help me where I could be wrong as I'm unable to find what is the issue. It works when I just use axios and fetch the data. |
Beta Was this translation helpful? Give feedback.
-
Would help if you could share the config that's passed to |
Beta Was this translation helpful? Give feedback.
-
This is the query. And for config I'm passing const { data: cpuUsageData, isFetching } = useCPUUsage(
{
visionSystemId: selectedVisionSystemId,
startTime: selectedTimeRange,
endTime: dayjs().unix(),
timeRange: selectedTimeRange
},
{ enabled: !!selectedTimeRange }
); This is the parent component where I'm rendering the import React, { useCallback, useMemo, useState } from 'react';
import { Select } from 'antd';
import dayjs from 'dayjs';
import {
ChartContainer,
CPUChart,
HardDiskChart,
RAMChart,
RejectionRatioChart,
SystemStatusChart,
} from '~/features/monitoring';
import { useCustomers } from '~/features/customers';
import { usePlants } from '~/features/plants';
import { useVisionSystems } from '~/features/vision-systems';
import PageHeader from '~/components/PageHeader';
const timeRangeOptions = [
{
label: '1 hour',
value: dayjs().subtract(1, 'h').unix()
},
{
label: '6 hours',
value: dayjs().subtract(6, 'h').unix()
},
{
label: '24 hours',
value: dayjs().subtract(24, 'h').unix()
}
]
export const Monitoring = () => {
const [selectedCustomerId, setSelectedCustomerId] = useState(null);
const [selectedPlantId, setSelectedPlantId] = useState(null);
const [selectedVisionSystemId, setSelectedVisionSystemId] = useState(null);
const [selectedTimeRange, setSelectedTimeRange] = useState('');
const { customers = [] } = useCustomers();
const { plants = [] } = usePlants(
{ customerId: selectedCustomerId },
{ enabled: !!selectedCustomerId }
);
const { visionSystems = [] } = useVisionSystems(
{ plantId: selectedPlantId },
{ enabled: !!selectedPlantId }
);
const customerDropDownOptions = useMemo(() => {
return customers?.map((customer) => ({
value: customer.customer_id,
label: customer.customer_name
}));
}, [customers]);
const plantDropDownOptions = useMemo(() => {
return plants?.map((plant) => ({
value: plant.plant_id,
label: plant.plant_name
}));
}, [plants]);
const visionSystemDropDownOptions = useMemo(() => {
return visionSystems?.map((visionSystem) => ({
value: visionSystem.vision_system_id,
label: visionSystem.vision_system_name
}));
}, [visionSystems]);
return (
<>
<PageHeader
heading="Monitoring"
actions={[
{
name: 'Customers Select',
type: 'dropdown',
placeHolder: 'Customer',
options: customerDropDownOptions,
handler: useCallback((value) => {
setSelectedCustomerId(value);
setSelectedPlantId(null);
setSelectedVisionSystemId(null);
}, [])
},
{
name: 'Plants Select',
type: 'dropdown',
placeHolder: 'Plant',
options: plantDropDownOptions,
value: selectedPlantId,
handler: useCallback((value) => {
setSelectedPlantId(value);
setSelectedVisionSystemId(null);
}, [])
},
{
name: 'Vision System Select',
type: 'dropdown',
placeHolder: 'Vision System',
options: visionSystemDropDownOptions,
value: selectedVisionSystemId,
handler: useCallback((value) => {
setSelectedVisionSystemId(value);
}, [])
}
]}
/>
<div className="my-10">
<Select
disabled={!selectedVisionSystemId}
options={timeRangeOptions}
onChange={setSelectedTimeRange}
placeholder="Select Period"
className="w-48"
/>
</div>
// CPU Chart
<ChartContainer heading="CPU">
<CPUChart {...{ selectedVisionSystemId, selectedTimeRange }} />
</ChartContainer>
</>
);
};``` |
Beta Was this translation helpful? Give feedback.
-
please provide a runnable reproduction, it's incredibly hard to help by just looking at videos and code snippets |
Beta Was this translation helpful? Give feedback.
@TkDodo @samhirtarif, Thanks for coming up guys, I have made a silly mistake and found out the root cause of it. It is not causing from react-query. Now it is working as expected.
Thanks again :)