React Native
...
Relay (GraphQL)
Users

Current User

11min

Get Current User using Relay for a React Native App

Introduction

After implementing user registration and login to your React Native App using Relay, you need to retrieve the currently logged user data to perform different actions and requests. In this guide we’re going to follow the Get User Logged GraphQL Cookbook guide and the Query Renderer to retrieve information about the current user.

The query as GraphQL is represented as:

GraphQL


At any time, you can access this project via our GitHub repositories to checkout the styles and complete code.

Goal

Create a component to get information about the current user.

Prerequisites

At any time, you can access this project via our GitHub repositories to checkout the styles and complete code.

1 - Creating the User Logged component

On SignIn component folder create a new file and name it UserLoggedRenderer.js.

Inside of UserLoggedRenderer.js, let’s create a component very similar to the Query Renderer tutorial, but in this case, just the query renderer is needed. With a valid session token into the application, the component will be called and will get the current user info.

The Query Renderer component will look like the following:

JS


The first @todo is should be implemented with the query to retrieve the info from the user logged. The Query used for this operation is decribed in Get User Logged GraphQL Cookbook guide.

GraphQL


The second @todo should be implemented with a function that will render the info about the user only if exists. If there is no error we are going to return therenderContentfunction described below. The function will render the current user info(email and username) in a secure way.

JS


You should implement the function before the QueryRenderer component. The final result of the component should look like this:

JS


2 - Importing the UserLoggedRenderer into SignIn component

Back into the FormSignIn component, replace the code which returns the current user info with the new User Logged component.

From

JS


To

JS


Don’t forget to import theUserLoggedRenderer:

JS


Now run yarn relay command to update with the new query:

yarn relay

Document image


Now, will be displayed the username or email with a valid session token. Otherwise, the component should not render and, the login will run.

Also, the useState userLogged can be removed from the code that not makes sense anymore.

Don’t forget to remove it from the onCompleted function into LogIn mutation.

Document image


Conclusion

The final result of this step should be the same as the last one. The info about it will be displayed but now followed by a username or email.

In the next doc, let’s create a button to do the log out of this user and clean the session, returning the app for login or sign-up flow.