DEV Community

Justin Saborouh
Justin Saborouh

Posted on

Data Fetching for Live React Apps

When starting your adventure of web development and programming, most of the starter apps and concepts are understood through single-page, static applications. This means that these apps are going to be same no matter what machine it's hosted on, and don't typically require an internet connection.

However, as seen with most of our day-to-day applications, there is always a sense of live-updating and client-server interaction to give the user a unique experience when using these apps. This is introduced in React as Data Fetching.

The method of updating and populating data on a webpage is defined as an AJAX call. React applications have a built-in library for these calls called window.fetch. With this fetch command, we can make calls to gather additional data.

fetch('http://example.com/ingredients.json')
  .then((res) => res.json())
  .then((data) => console.log(data));
Enter fullscreen mode Exit fullscreen mode

The first parameter pertaining to the fetch invocation tells React where to gather the information from. Prioritizing the destination to be a json file will return less steps converting the data received. The result isn't technically the json body but a promise that will eventually turn into a response res element that is converted to json format. Then, with the last .then statement, we can finally instruct what to do with the gathered data.

The first time we can appropriately program a fetch command is in conjunction with the useEffect() hook. After the first stage of a page rendering, which is simply loading the DOM elements and basic HTML, another 'reload' is ran where most components are rendered, as well as text content and image sources. Here is where we'd want to call the useEffect hook to gather any outside data we'd need to use.

import React, { useState, useEffect } from "react";
function App() {
  const [recipesList, setRecipesList] = useState([]);

  useEffect(() => {
    fetch("http://api.open-cooking.org/recipes.json")
      .then((res) => res.json())
      .then((data) => {
        setRecipesList(data.recipes);
      });
  }, []);

  return <div>{peopleInSpace.recipes((recipe) => recipe.ingredients)}</div>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

The example code here let's us call a fetch during the initial 'second' load of a React application, sets the data to a readable json format, and adds the data to our state variable of recipesList.

Another time to call a fetch argument is during an event signal for any DOM element. Let's say you needed to retrieve and load data after a button or an event was clicked.

function handleClick() {
  fetch("http://api.open-notify.org/recipes.json")
    .then((res) => res.json())
    .then((json) => setData(json));
}

return <button onClick={handleClick}>Click to Fetch!</button>;
Enter fullscreen mode Exit fullscreen mode

On click, the button will call a function that accesses data from a URL and assigns it to a state variable.

These are the two primary scenarios to call and fetch data from external sources. With this expanded perspective of react building, we can build slightly more advanced applications that are interactive with the user to alter and retrieve data.

Resources
AJAXs and APIs - React (https://reactjs.org/docs/faq-ajax.html#example-using-ajax-results-to-set-local-state)

Using the Fetch API - mdn web docs (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

Using the Effect Hook - React
(https://reactjs.org/docs/hooks-effect.html)

Top comments (0)