React Query use custom hook with useQuery on click event

592 views Asked by At

I have a button that when the customer click it I need to fetch data from my database, for this I use React Query and I encountered a problem where I tried to use custom hook inside event handler which is not possible, I'm stuck on figuring out how to use it

this is my custom hook

 export const useGuestInfo = () => {
  const { bookingId } = useSearchParams();
  const { isGettingGuestInfo, data: guestInfo } = useQuery({
    queryKey: [`guest`, bookingId],
    queryFn: (bookingId) => getGuestInformation(bookingId),
  });
  return { isGettingGuestInfo, guestInfo };
};

and this is my Event handler I'm trying to use

  const onGuestUpdate = () => {
    setUpdateGuestModal(true);
    searchParams.set("bookingId", bookingId);
    setSearchParams(searchParams);
    const { isGettingGuestInfo, guestInfo } = useGuestInfo();
  };

the error i'm getting is Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component

how would you do it?

another question, do you always need to use useQuery() when trying to fetch data from api or database? or you can do it in normal functions too? i'm new to programming :)

1

There are 1 answers

0
Bhavesh Parvatkar On

You can keep the hook separate and conditionally call it only when bookingid is set.

The hook takes bookingId as parameter. The enabled property will call the API only when bookingId is available.

hooks.js

export const useGuestInfo = (bookingId) => {
  const { isFetching: isGettingGuestInfo, data: guestInfo } = useQuery({
    queryKey: [`guest`, bookingId],
    enabled: bookingId !== null,
    queryFn: () => getGuestInformation(bookingId),
  });
  return { isGettingGuestInfo, guestInfo };
};

App.js

We declared useGuestInfo but it wont call the API until bookingId is not null.

onGuestUpdate method will set bookingId in searchParams and then useGuestInfo will be called.

const { bookingId } = useSearchParams();
const { isGettingGuestInfo, guestInfo } = useGuestInfo(bookingId)

const onGuestUpdate = () => {
    setUpdateGuestModal(true);
    searchParams.set("bookingId", bookingId);
    setSearchParams(searchParams);
};

I am not sure how setSearchParams works in your code but I guess you might replace const { bookingId } = useSearchParams(); with setSearchParams data