Apologies as I'm fairly new to React and couldn't find the answer when searching but accept I might be using this wrong.
I have several pages that utilise useQuery from Apollo and when "loading" variable is false it can then process the data and render which is easy enough.
However, I want to create a new file called GetCustomerID.jsx and have an arrow function which, when supplied with a user ID, will run a gql query and return the customer ID value. Not render components, just return the value.
The trouble is that once this is called from within another page it always just returns "loading"
const myQuery = gql`
query GetCustomerID($id: ID!) {
user(id: $id) {
data {
id
attributes {
customer {
data {
id
}
}
}
}
}
}
`;
const GetCustomerID = () => {
const [userId, setUserID] = useState(localStorage.getItem("userid"));
const [custId, setCustId] = useState();
const { loading, error, data } = useQuery(myQuery, {
variables: {
id: userId
}
});
if(loading){
return "loading"
}
if (error) {
console.log(error);
return "error";
}
setCustId(data.attributes.customer.id);
console.log(custId);
return custId;
};
Call from elsewhere:
const [custId, setCustId] = useState();
let myVal = GetCustomerID();
setCustId(myVal)
Any help would be much appreciated and if I'm fundamentally misunderstanding useQuery for what I'm trying to achieve then apologies