I’m looking for the right method to use useQuery with variables fetching from another request.
I’ve got a function to get the foodtruck of the logged user. And once foodtruck is defined, I want to call my Query.
import React, {useEffect, useState} from 'react'
import {useQuery, gql } from "@apollo/client";
import { getAxiosAPI } from '../../lib/api';
const gqlReservationsByFoodtruck = gql`
query Reservations ($foodtruck: ID!) {
reservations ( where: { foodtruck: $foodtruck }) {
schedule {
id
}
}
}
`
const Query = ({foodtruck}) => {
const { loading, error, data } = useQuery (gqlReservationsByFoodtruck,
{ variables: {foodtruck:foodtruck && foodtruck.id} }
);
console.log(data, 'data')
};
const parseVaiables = () => {
const [foodtruck, setFoodtruck] = useState(null)
//Get Foodtruck from User ID
useEffect(() => {
const getFoodtrucks = async () => {
const response = await getAxiosAPI(`/foodtrucks?user.lastName=Borsti`);
setFoodtruck(response.data[0])
}
getFoodtrucks()
}, [Query({foodtruck})])
return (
<>
</>
)
}
export default parseVaiables
As you can see, I call my function Query in the input of my useEffect. It’s the only place when I didn’t get a infinite loop or a react queue error.
Also, like this, it’s working, but my Query function is still call with an empty variable foodtruck, so I get undefined data and a graphql error : "“message”:“Variable "$foodtruck" of non-null type "ID!" must not be null.”
What can I do to make it right ?
Thanks a lot !