1

I've this hook:

import axios from "axios";
import { useQuery } from "react-query";

const fetchCartPreview = (cartId, userId) => {
  console.log("Init query");
  axios
    .get(
      `${process.env.REACT_APP_API_BASE_URL}/carts/${cartId}/checkout_preview`,
      {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        params: { user_id: userId },
      }
    )
    .then((response) => console.log("Response from hook", response.data));
};

export default function useCartPreview(cartId, userId) {
  return useQuery(
    ["cart_preview", cartId, userId],
    async () => {
      const data = await fetchCartPreview(cartId, userId)
      return data
    },
    { onSuccess:  console.log("Finish query") }
  );
}

The console.log(response.data) it's ok, the problem is that the useQuery, onSuccess, returns data: undefined and T don't know why..

Console.log in the component that calls the hook

Thank you!

1
  • You are not returning anything from fetchCartPreview(), therefore data will be undefined Commented Nov 17, 2021 at 19:35

2 Answers 2

1

Is it still not working if you are returning response.data from fetchCartPreview ?

Can you try adjusting your function like this:

const fetchCartPreview = (cartId, userId) => {
  console.log("Init query");
  axios
    .get(
      `${process.env.REACT_APP_API_BASE_URL}/carts/${cartId}/checkout_preview`,
      {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json"
        },
        params: { user_id: userId }
      }
    )
    .then((response) => {
      console.log("Response from hook", response.data);
      return response.data;
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Tank you orotype but it still not working, I've tried de same before. It seems that the react-query onSuccess status execute before the axios response.
0

Two issues:

  1. onSuccess needs to be a function:
{ onSuccess: () => console.log("Finish query") }
  1. You need to actually return something from your queryFn. By doing:
axios
    .get(url)
    .then((response) => console.log("Response from hook", response.data));

you are transforming your promise in the .then part, logging the data, but then you return undefined, which will put undefined in the react-query cache. if you must log in the query fn, you have to make sure to actually return something from .then:

axios
  .get(url)
  .then(response => {
    console.log(response.data)
    return response //or return response.data
  })

but it is better to keep logging out of the queryFn and use the onSuccess callback for that.

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.