DEV Community

Cover image for Connecting a gif API on ReactJS without a backend
Clemenshemmerling for KOR Connect

Posted on • Updated on

Connecting a gif API on ReactJS without a backend

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

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

Image description

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

npx create-react-app giphy
Enter fullscreen mode Exit fullscreen mode

Once the React project is created go to korconnect.io and click on “View Details.”

Alt Text

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

npm install @material-ui/core
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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("");
Enter fullscreen mode Exit fullscreen mode

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);  
      });  
  };
Enter fullscreen mode Exit fullscreen mode

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);  
      });  
  };
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 is some additional information pertaining to Testing and Production Modes on KOR Connect.

Image description

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

Alt Text

Top comments (0)