2

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?

1
  • 2
    I think the error is due to initial state cleanResponse(products?.products || []). What do you think ? Commented Aug 16, 2022 at 3:35

2 Answers 2

2

The error is due to initial state you can do as below to prevent error.

cleanResponse(products?.products || [])

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.