MattJSUK
MattJSUK

Reputation: 15

useQuery Hook Data

I can return a query's data using useQuery no problem. I'm trying to retrive a user with the following query but when accessing data.user my app throws an error to say data is undefinded.

const userQuery = gql`
{
user {
   id
   email
 }
 } `;


export default NavWrapper = () => {
const { loading, error, data }  = useQuery(userQuery);
console.log(data);

if (loading) return <ActivityIndicator size="large"/>
if (!data) return <Login/>;
return <Navigator/>;
}

The above works fine and retrives the user within an object, but I need to render the login comp based on the actual user rather than the data wrapper. Any ideas? must be simple...

Upvotes: 0

Views: 252

Answers (1)

JustinTRoss
JustinTRoss

Reputation: 787

Likely you have unsafe property access and are trying to use data.user before the query finishes. Essentially, your code is operating under the assumption data will always be present, whereas the nature of a query is such that there is a beginning unqueried state in which there is no data, followed by a loading state during which the query is being made and no data is available, followed by a somewhat final state in which data is made available. Your code should be prepared for all the states.

To account for these situations, you should use safe property access like so:

const user = data ? data.user : null

Alternatively, you can use a safe property access lib like idx:

const user = idx(data, _ => _.user) || null

Further, you'll want to make sure any components consuming your user data are prepared for the case in which the user is not available to them.

Note: data.user isn't referenced any where in the code you linked. It'll be helpful to know exactly where you're calling it (e.g. in body of NavWrapper vs Login or elsewhere).

Upvotes: 1

Related Questions