Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
Using Apollo's useQuery to return a value, not render

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

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda