Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 17, 2021 02:14 am GMT

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

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 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

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/).

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;

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

Alt Text


Original Link: https://dev.to/korconnect/connecting-a-gif-api-on-reactjs-without-a-backend-3fj7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To