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?