1

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.

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185
  • I would probably `const {returnUser: user} = data;` This assigns the value of `data.returnUser` to `const user` and allows you to use `user.name`, `user.someProp` see: [Destructuring and rename property](https://stackoverflow.com/questions/57065348/destructuring-and-rename-property) – pilchard Sep 18 '21 at 12:21
  • Sure, but wouldn't it be nice if it could be done in a single line? :) – Peter Boomsma Sep 18 '21 at 12:22
  • `const { error, loading, data: { returnUser: user } } = useQuery...` – pilchard Sep 18 '21 at 12:23
  • 1
    Btw it's `.name` not `.user_name` – Bergi Sep 18 '21 at 12:46

2 Answers2

2

Got the answer thanks to @Pilchard:

const {error, loading, data: {returnUser: user} = {}} = useQuery(resolvers.queries.ReturnUser, {
    variables: {userId: parseInt(id)},
  });
Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185
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

Jayendra Sharan
  • 1,043
  • 6
  • 10