Categories
JSON

Working with JSON — Using Fetch API with React

Spread the love

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON with React and Fetch API.

Making HTTP Requests with React

React is a view library, so it doesn’t come with any way to make HTTP requests.

To do this, we have to use our own HTTP client library.

Most modern browsers today comes with the Fetch API.

We can use it with the useEffect hook.

To use it, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [answer, setAnwser] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const answer = await res.json();
    setAnwser(answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);
  return <div className="App">{JSON.stringify(answer)}</div>;
}

to make a GET request to an endpoint with the fetch function.

It returns a promise that resolves to the data and then we call json to get the data from the JSON.

Then we call setAnswer to set the answer state.

The empty array in 2nd argument means that we only run the callback when the component mounts.

Also, we can move the getAnswer function into its own hook by writing:

import React, { useEffect, useState } from "react";

const useAnswer = () => {
  const [answer, setAnwser] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const answer = await res.json();
    setAnwser(answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);
  return answer;
};

export default function App() {
  const answer = useAnswer();
  return <div className="App">{JSON.stringify(answer)}</div>;
}

We move all the logic to get the response from the API endpoint to its own hook.

Then we can keep our component squeaky clean with no side effects.

To make a POST request with the Fetch API, we can write:

import React, { useEffect, useState } from "react";

const makeRequest = async (data) => {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos", {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  });
  const response = await res.json();
  return response;
};

export default function App() {
  const submit = async () => {
    const res = await makeRequest({
      title: "delectus aut autem",
      completed: false
    });
    console.log(res);
  };

  return (
    <>
      <button onClick={submit}>add todo</button>
    </>
  );
}

We added the makeRequest function that calls fetch with the URL to make the request to an an object with the options for our request.

The method property is the request method.

The mode is the request mode. 'cors' makes a cross-origin request.

cache set to 'no-cache' disables cache.

credentials sets the cookies origin.

headers has the HTTP request headers that we want to send.

body has the HTTP request body.

When we click the ‘add todo’ button, then submit function makes the request with the makeRequest function.

Then the response data is returned with the promise returned from the makeRequest function and logged from the console log.

Conclusion

We make HTTP requests in a React app with the Fetch API.

Leave a Reply

Your email address will not be published. Required fields are marked *