Build a React Front-End interacting with Hasura Back-End trough GraphQL— Part 2

React/QraphQl/Hasura

Welcome everyone,

If you didn’t read the first part, here is the link : Part 1

In he first part, we have created the server, Backend with Hasura and GraphQL, so we need to build a Frontend to consume it.
I have chosen React as a tool to do the mission.

1. Set-up the environment :

→ First of all, let’s create a new React app using terminal :

npx create-react-app movies

→ Then, inside the app folder, we run the command :

npm install graphql @apollo/client react-router-dom @material-ui/core @material-ui/styles

Each of these tools are for a good reason. In fact, graphql and apollo are for GraphQl Queries, and Material-UI is for styling.

Open your favorite editor and start the React app with :

npm start

2. Display the movies :

We will create a components folder, in which we will store all of our components.

Let’s edit the App component :

In the App component, we set up a graphQL client (The backend) with Apollo, and wrap the application with the Apollo Provider.

Then we will be creating the component that will display the movies from the API in the screen :

The component Movies has a job. It is to map through movies that it bring them from the back-end using a GraphQL query.
The query gives us back all the movies ordered by it’s modification date. The Component Movies display them all;

And of course, after we put some styles, here is the result :

3. Add a Serach Bar :

Now, we will add a search bar by adding a state: {title: ‘’}to App, and an input which have a handler searchHandler, it’s triggered by changing the value of the input.
Once the input value change, the handler will set the title value on the state to the input value.
Notice that the component Movies takes as prop the title in the state, it means when the title value change, it’s triggering the Movies component to re-render.

We have to adapt the Movies component to act as the title change, so we’ll use the filter() function of JavaScript.

This line of code takes all the movies and filters them to keep those whose titles include the title sought.

Here is the final result :

Thank you for reading !

Software engineer @AE