The simplest way to fetch data from APIs in NextJS

Before We Begin

this is very important and simple too , but if you pay attention to it , you will understand how to use it.
you need abit of react knowledge to understand this.

First Download axios

npm i axios


This content originally appeared on DEV Community and was authored by Hamdy Saad

1_ycqhUTo1LqydeC355iHRoA.jpeg

Before We Begin

  • this is very important and simple too , but if you pay attention to it , you will understand how to use it.
  • you need abit of react knowledge to understand this.

First Download axios

npm i axios

what is axios ?

  • axios is a library that helps you make HTTP requests from the browser.
  • it is a promise based library.
  • it is a tool that helps you make HTTP requests from the browser.
  • so we will use it cuz it's the simplest way to get data from the API .

NextJS and Fetch

in NextJS , we use the fetch api to get data from the API .
but notice that in server side rendering , we can't use the data in the component directly, we need to manage the status by useState & useEffect.

Let's Go ?

first get the url of the api then sace it .

  const url = "https://catfact.ninja/fact";

then let's begin to fetch the data from the api .(YOU HAVE TO INSTALL AXIOS 😬 !!)

##  fetch data
 // fetch data .
  function getData() {
    axios
      .get(url)
      .then((res) => {
       //put the resulted data in the console for testing purposes
        console.log(res.data);
        setRepo(res.data);
      })
      //handle the error
      .catch((err) => {
        console.log(err);
      });
  }
  • Now you have the data in the console (the clint), Now how we could put it inside a component ??!

Put it in a component .

  • Let's say you builtin a page to display a fact every 5 seconds how could you do that ?
  • Here is an example of what we will do GO THERE !.

was nice ha ? 😏

  • any way, we will do this exactly but the logical part, you can see the full repo here GO THERE !.

this is an empty component

  export default function Home() {


       return (
       <div>
           <h1></h1>
       </div>
       );
   };

create the status that will manage the data

- we will use the useState hook to manage the data.
- we will use the useEffect hook to manage the status.
- why tho ? cuz it's a server side rendering you can't handle a client side operations there .
or you will face errors like :
 ```
 Hydration failed because the initial UI does not match what was rendered on the server.
 ```

or

Text content does not match server-rendered HTML.
  • so be aware of the status.
useEffect(() => {
    let interval = setInterval(() => {
      getData();
      setLoading(!loading);
      setDot(dota);
      setEmoji(emojia);
    }, 5000);

here we used interval to get the data every 5 seconds.
the put every function that we want to update it's status and return it.(but there is no return yet)

the functions

// to get a rendom number of dots
 function dot() {
    return dots[Math.floor(Math.random() * dots.length)];
  }
  // to get a rendom number of emojis
    function emoji() {
    return emojiArray[Math.floor((Math.random() * emoji.length) / 2)];
  }
  // and we have setLoading state to display a simple text when the data is not loaded yet.
  // and of course we have getData .(the data itself)

so put it all together and you will get the result 😍 .

Now for what you want 😏

the source code

  • you can see it hereGO THERE !.
  • give it a star plz or jut copy this :
import styles from "../styles/Home.module.css";
import axios from "axios";
import { useState, useEffect } from "react";

export default function Home() {
  let [repo, setRepo] = useState([]);
  let [loading, setLoading] = useState(true);
  let [dota, setDot] = useState([]);
  let [emojia, setEmoji] = useState([]);

  const url = "https://catfact.ninja/fact";
  // fetch data .
  function getData() {
    axios
      .get(url)
      .then((res) => {
        console.log(res.data);
        setRepo(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  function dot() {
    return dots[Math.floor(Math.random() * dots.length)];
  }
  function emoji() {
    return emojiArray[Math.floor((Math.random() * emoji.length) / 2)];
  }
  // put it inside useEffect hook .
  useEffect(() => {
    let interval = setInterval(() => {
      getData();
      setLoading(!loading);
      setDot(dota);
      setEmoji(emojia);
    }, 5000);

    return () => clearInterval(interval);
  }, [loading]);

  const emojiArray = [
    "😍",
    "πŸ₯°",
    "😘",
    "πŸ˜—",
    "πŸ˜™",
    "😚",
    "πŸ˜‹",
    "πŸ˜›",
    "😝",
    "😜",
    "πŸ€ͺ",
    "😏",
    "πŸ˜’",
    "😞",
    "πŸ˜”",
    "😟",
    "πŸ˜•",
    "πŸ™",
    "☹️",
    "πŸ˜–",
    "😫",
    "😩",
    "πŸ₯Ί",
    "😒",
    "😭",
    "😀",
    "😠",
    "😑",
    "🀬",
    "🀯",
    "😳",
    "πŸ₯΅",
    "πŸ₯Ά",
    "😱",
    "😨",
    "😰",
    "πŸ˜₯",
    "πŸ˜“",
    "πŸ€—",
    "πŸ€”",
    "🀭",
    "🀫",
    "πŸ€₯",
    "😢",
    "😐",
    "πŸ˜‘",
    "😬",
  ];
  const dots = ["...", "..", "."];
  return (
    <div data-reactroot='' className={styles.text}>
      <h3 className={styles.h3}>Featched Data {emoji()}</h3>
      <h1>New fact every 5 sec </h1>

      <h4>{!repo.fact ? "loading ..." : repo.fact}</h4>

      <h6 style={{ color: "#F0F8FF", fontSize: "15px" }}>
        {repo.fact ? "Loading new one  " : ""}
        {dot()}
      </h6>
    </div>
  );
}

have a wonderful day πŸ₯° .


This content originally appeared on DEV Community and was authored by Hamdy Saad


Print Share Comment Cite Upload Translate Updates
APA

Hamdy Saad | Sciencx (2022-05-01T06:24:46+00:00) The simplest way to fetch data from APIs in NextJS. Retrieved from https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/

MLA
" » The simplest way to fetch data from APIs in NextJS." Hamdy Saad | Sciencx - Sunday May 1, 2022, https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/
HARVARD
Hamdy Saad | Sciencx Sunday May 1, 2022 » The simplest way to fetch data from APIs in NextJS., viewed ,<https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/>
VANCOUVER
Hamdy Saad | Sciencx - » The simplest way to fetch data from APIs in NextJS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/
CHICAGO
" » The simplest way to fetch data from APIs in NextJS." Hamdy Saad | Sciencx - Accessed . https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/
IEEE
" » The simplest way to fetch data from APIs in NextJS." Hamdy Saad | Sciencx [Online]. Available: https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/. [Accessed: ]
rf:citation
» The simplest way to fetch data from APIs in NextJS | Hamdy Saad | Sciencx | https://www.scien.cx/2022/05/01/the-simplest-way-to-fetch-data-from-apis-in-nextjs/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.