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

343
Visualizações
How to destructure nested data returned from useQuery?

I have an Apollo query:

const { error, loading, data: user } = useQuery(resolvers.queries.ReturnUser, {
    variables: { userId: parseInt(id) },
  });

The data object returned from the query has another object called returnUser. So the actual object is:

data: {
  returnUser: {
    name: 'Some Name'
  }
}

In my JSX I want to output the data:

return (
  <div>
    { user ?
      <p>Profile {user.returnUser.name}</p> :
      <div>User not found</div> }
  </div>
);

As you can see I need to access the returnUser object on the user object to get the actual user data. This is not great. Is there any way to destructure the data object from the useQuery so I can assign the nested object to user?

//edit: While this looks like a duplicate question, the answer is different due to the async nature of useQuery. If you don't set a default value you'll get an error.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Got the answer thanks to @Pilchard:

const {error, loading, data: {returnUser: user} = {}} = useQuery(resolvers.queries.ReturnUser, {
    variables: {userId: parseInt(id)},
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

You can follow the same nesting while deconstructing the data.

e.g.

const data = {
  anotherLevel: {
     returnUser: {
      name: 'Some Name'
    } 
  }
}

const { anotherLevel: {returnUser: { name }}} = data;

console.log(name); // prints Some Name

about 4 years ago · Juan Pablo Isaza Relatório
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