Reputation: 701
I have a helper function to clean up the response from a useQuery call to an api. Here is the function:
export const cleanResponse = function (data) {
let x = [];
let y = [];
data.forEach((item) => {
x.push(item.title);
y.push(item.price);
});
return { titles: x, prices: y };
};
In my main components I'm using useQuery to get the data then applying the above function to clean it up and prepare it for plotting:
const {
data: products,
isLoading,
isError,
} = useQuery(['products'], () => {
return axios('https://dummyjson.com/products/').then((res) => res.data);
});
const cleanData = cleanResponse(products.products);
const titles = cleanData?.titles;
const prices = cleanData?.prices;
Then I'm rendering a simple bar chart passing the data as props:
<BarChart titles={titles} prices={prices} />
I'm getting the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'products')
What am I missing here? Should my cleanResponse function be async because it's accepting data from an api?
Upvotes: 2
Views: 882
Reputation: 28833
while the query is still running, you component renders with data:undefined
.
one way to solve this is to check for undefined before you do your transformation. Other approaches are doing the data transformation at a different time, e.g. in the query function after fetching:
const {
data,
isLoading,
isError,
} = useQuery(['products'], () => {
return axios('https://dummyjson.com/products/')
.then((res) => res.data)
.then((data) => cleanResponse(data.products))
});
That way, the cleaned data will be stored in the cache already and data
returned from useQuery
will be the cleaned data.
Other approaches include using the select
option. You can read more about that in my blog post about react-query data transformations.
Upvotes: 1
Reputation: 799
The error is due to initial state you can do as below to prevent error.
cleanResponse(products?.products || [])
Upvotes: 2