Connecting a gif API on ReactJS without a backend
Tags: react, node, aws, serverless
Published: 2021-09-17 02:14:42

The simplest way to connect an API to a frontend with best practices applied automatically.
-------------------------------------------------------------------------------------------

We will create a gif search engine using KOR Connect.

Prior to starting you will need to connect your API to KOR Connect, please do so following this documentation: [https://kor-comunity.gitlab.io/kor-connect/adir/GETSTARTED.html](https://kor-comunity.gitlab.io/kor-connect/adir/GETSTARTED.html)

If you would like, you can test your connection with Postman or another API testing tool.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aefff9tfinjyadmnjey0.png)

After making the API connection above, create a React project using this command.

```
npx create-react-app giphy
```

Once the React project is created go to [korconnect.io](http://korconnect.io) and click on “View Details.”

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

Inside View Details select the “Snippets” tab and then choose React. Install the dependencies shown in the snippet. _Dependencies must be installed inside the project folder_

```
npm install — save react-google-recaptcha-v3 axios
```

After installing the necessary dependencies import the libraries in the snippet, also replace the provider with the one shown by the snippet.

The index.js should look like this.

```
import React from 'react';  
import ReactDOM from 'react-dom';  
import './index.css';  
import App from './App';  
import reportWebVitals from './reportWebVitals';  
import {  
  GoogleReCaptchaProvider,  
} from 'react-google-recaptcha-v3';ReactDOM.render(  
  <GoogleReCaptchaProvider reCaptchaKey="yourSnippetKey">  
    <App />  
  </GoogleReCaptchaProvider>,  
  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](https://bit.ly/CRA-vitals)  
reportWebVitals();
```

Now go to the App.js file and replace it with the snippet, it should look like this.

```
import React, { useEffect }  from 'react';  
import axios from 'axios';  
import {  
  useGoogleReCaptcha  
} from 'react-google-recaptcha-v3';const App = () => {  
  const { executeRecaptcha } = useGoogleReCaptcha();// Create an event handler so you can call the verification on button click event or form submit  
  const handleGet = async () => {  
    if (!executeRecaptcha) {  
      console.log('Execute recaptcha not yet available');  
    }const token = await executeRecaptcha('submit');  
    // Do whatever you want with the token  
    console.log(token);  
    axios.get('[https://yourSnippetURL/'](https://yourSnippetURL/'), { headers: { token, 'x-api-key': 'yourSnippetToken' } })  
    .then(response => {  
      console.log(response)  
    })  
    .catch(error => {  
      console.log(error)  
    })  
  };// You can use useEffect to trigger the verification as soon as the component being loaded  
  useEffect(() => {  
    if (executeRecaptcha) {  
      handleGet();  
    }}, \[executeRecaptcha\]);useEffect(() => {  
    const el = document.querySelector('.grecaptcha-badge');  
    el.style.display = 'none';  
  }, \[\]);return (  
    <>  
    <h1>Hello World</h1>  
    </>  
  );  
};export default App;
```

Now modify the code to adapt it to the application, to do this install a style library (we will use [https://material-ui.com/](https://material-ui.com/)).

```
npm install @material-ui/core
```

In App.js import the following elements and useState.

```
import React, { useEffect, useState } from "react";  
import Grid from "[@material](http://twitter.com/material)\-ui/core/Grid";  
import TextField from "[@material](http://twitter.com/material)\-ui/core/TextField";
```

Now add two constants to save the API data, the code should look like this.

```
const \[data, setData\] = useState(null);  
const { executeRecaptcha } = useGoogleReCaptcha();  
const \[headerInfo, setHeaderInfo\] = useState("");
```

Now create a function to allow users to search for any gif, add the necessary path in order to carry out this search feature. The code should look like this.

```
const handleSearch = async (event) => {  
    const token = await executeRecaptcha("submit");  
    axios  
      .get(  
        \`[https://yourSnippetURL/v1/channels/search?q=${event.target.value}\`](https://yourSnippetURL/v1/channels/search?q=${event.target.value}`),  
        {  
          headers: {  
            token,  
            "x-api-key": "yourSnippetToken",  
          },  
        }  
      )  
      .then((response) => {  
        setData(response.data.data);  
      })  
      .catch((error) => {  
        console.log(error);  
      });  
  };
```

Now we will modify the handleGet function to be able to store the response in a constant, the code should look like this.

```
const handleGet = async () => {  
    if (!executeRecaptcha) {  
      console.log("Execute recaptcha not yet available");  
    }const token = await executeRecaptcha("submit");  
    // Do whatever you want with the token  
    console.log(token);  
    axios  
      .get("[https://](https://clemensk.korconnect.io/GIPHY/v1/gifs/random)[yourSnippetURL](https://yourSnippetURL/v1/channels/search?q=${event.target.value}`)[/v1/gifs/random](https://clemensk.korconnect.io/GIPHY/v1/gifs/random)", {  
        headers: {  
          token,  
          "x-api-key": "yourSnippetKey",  
        },  
      })  
      .then((response) => {  
        setHeaderInfo(response.data.data);  
      })  
      .catch((error) => {  
        console.log(error);  
      });  
  };
```

Finally, we will add an input to do the searches and we will also add a map to display our result, the App.js should look like this.

```
import React, { useEffect, useState } from "react";  
import axios from "axios";  
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";  
import Grid from "[@material](http://twitter.com/material)\-ui/core/Grid";  
import TextField from "[@material](http://twitter.com/material)\-ui/core/TextField";const App = () => {  
  const \[data, setData\] = useState(null);  
  const { executeRecaptcha } = useGoogleReCaptcha();  
  const \[headerInfo, setHeaderInfo\] = useState("");const handleSearch = async (event) => {  
    const token = await executeRecaptcha("submit");  
    axios  
      .get(  
        \`[https://clemensk.korconnect.io/GIPHY/v1/channels/search?q=${event.target.value}\`](https://clemensk.korconnect.io/GIPHY/v1/channels/search?q=${event.target.value}`),  
        {  
          headers: {  
            token,  
            "x-api-key": "2y91wVZrme9mN93HMeGBv5wH9JoxVm8m5Mv61BQN",  
          },  
        }  
      )  
      .then((response) => {  
        setData(response.data.data);  
      })  
      .catch((error) => {  
        console.log(error);  
      });  
  };// Create an event handler so you can call the verification on button click event or form submit  
  const handleGet = async () => {  
    if (!executeRecaptcha) {  
      console.log("Execute recaptcha not yet available");  
    }const token = await executeRecaptcha("submit");  
    // Do whatever you want with the token  
    console.log(token);  
    axios  
      .get("[https://clemensk.korconnect.io/GIPHY/v1/gifs/random](https://clemensk.korconnect.io/GIPHY/v1/gifs/random)", {  
        headers: {  
          token,  
          "x-api-key": "2y91wVZrme9mN93HMeGBv5wH9JoxVm8m5Mv61BQN",  
        },  
      })  
      .then((response) => {  
        setHeaderInfo(response.data.data);  
      })  
      .catch((error) => {  
        console.log(error);  
      });  
  };// You can use useEffect to trigger the verification as soon as the component being loaded  
  useEffect(() => {  
    if (executeRecaptcha) {  
      handleGet();  
    }  
  }, \[executeRecaptcha\]);return (  
    <>  
      <Grid xs={12}>  
        <h1 className="center-align">Gif Explorer</h1>  
      </Grid>  
      <Grid  
        xs={12}  
        container  
        direction="row"  
        justifyContent="center"  
        alignItems="center"  
      >  
        <img src={headerInfo.image\_url} alt="logo" />  
      </Grid>  
      <Grid xs={12}>  
        <TextField  
          id="standard-basic"  
          label="Search"  
          fullWidth  
          onChange={(e) => handleSearch(e)}  
        />  
      </Grid>  
      {data && data.map(  
        (gif) =>  
          gif.banner\_image && (  
            <Grid  
              xs={12}  
              md={3}  
              key={data.id}  
              container="row"  
              justifyContent="center"  
              alignItems="center"  
            >  
              <img src={gif.banner\_image} alt="image" />  
            </Grid>  
          )  
      )}  
    </>  
  );  
};export default App;
```
Once we are ready to deploy the project to production we have to change the Connection Mode from Test Mode to Production Mode, this will turn on additional security.

[Here](https://kor-comunity.gitlab.io/kor-connect/adir/TESTINGPRODUCTIONMODES.html) is some additional information pertaining to Testing and Production Modes on KOR Connect.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt1mq4z69v4d2c90ytlp.png)

The gif finding app should be ready! KOR Connect is taking care of all the actions required behind the scenes.

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