Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!