Consumindo API GraphQL usando React e Apollo Client
Tags: react, graphql
Published: 2021-03-01 00:08:35

No tutorial de hoje, iremos consumir uma API GraphQL usando React e Apollo Client. 

A API GraphQL será a seguinte: https://rickandmortyapi.com/graphql

Vou deixar abaixo dois links que falam sobre GraphQL e Apollo para quem quiser entender melhor antes de prosseguir com o tutorial 

https://adrianolisboa.com/o-minimo-que-voce-precisa-saber-sobre-graphql-para-nao-passar-vergonha-em-uma-conversa/

https://www.redhat.com/pt-br/topics/api/what-is-graphql

Vamos à prática! 

Crie um projeto usando **CRA(Create React App)** e após isso, adicione a dependência abaixo

```sh
yarn add graphql @apollo/client
```

## Estrutura do projeto

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uw85q6avvfw3m1uysxgs.png)

## src/service/index.js

```js
import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://rickandmortyapi.com/graphql",
  cache: new InMemoryCache(),
});

export default client;
```

## src/querys/index.js

```js
import { gql } from "@apollo/client";

const INFO_PERSON = gql`
  query {
    characters {
      results {
        name
        species
        gender
        image
      }
    }
  }
`;

export default INFO_PERSON;
```

## src/App.js

```js
import { useQuery } from "@apollo/client";

import INFO_PERSON from "./querys/index";

import "./App.css";

function App() {
  const { loading, error, data } = useQuery(INFO_PERSON);

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>an error occurred...</p>;
  }

  return (
    <section className="parent">
      {data.characters.results.map((person, index) => (
        <div className="card" key={person.name}>
          <img src={person.image} alt="Avatar" style={{ width: "100%" }} />
          <div className="container">
            <h4>
              <b>{person.name}</b>
            </h4>
            <p>
              <b>GENDER:</b> {person.gender}
            </p>
            <p>
              <b>SPECIE:</b> {person.species}
            </p>
          </div>
        </div>
      ))}
    </section>
  );
}

export default App;
```

## /src/index.js

```js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { ApolloProvider } from "@apollo/client";

import client from "./service/index";

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```

## src/App.css

```css
.parent {
     display: flex;
     flex-wrap: wrap;
     justify-content: space-between;
}
 .card {
     margin: 5%;
     box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
     transition: 0.3s;
     width: 20%;
}
 .card:hover {
     box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}
 .container {
     padding: 2px 16px;
}

```

## Resultado

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdjda7f3j7vo1vxccg7w.png)

É isso! Qualquer dúvida, sugestão ou crítica, basta comentar abaixo :)