DEV Community

Md Yusuf
Md Yusuf

Posted on

React Data Fetching: Techniques for REST APIs and GraphQL Queries

In React, you can fetch data from APIs using both REST and GraphQL. Here's a brief overview of how to handle each:

1. Fetching Data from REST API:

You can use fetch, axios, or other libraries to interact with REST APIs. Here's an example using the fetch method.

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

const FetchData = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        return response.json();
      })
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default FetchData;
Enter fullscreen mode Exit fullscreen mode

2. Fetching Data from GraphQL:

You can use libraries like apollo-client or just use fetch for GraphQL queries.

Here’s an example using fetch for GraphQL queries:

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

const FetchGraphQL = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchGraphQL = async () => {
      const query = `
        {
          posts {
            id
            title
          }
        }
      `;

      try {
        const response = await fetch('https://example.com/graphql', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ query }),
        });

        const result = await response.json();
        setData(result.data.posts);
        setLoading(false);
      } catch (error) {
        setError(error.message);
        setLoading(false);
      }
    };

    fetchGraphQL();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default FetchGraphQL;
Enter fullscreen mode Exit fullscreen mode

Key Libraries:

  • REST: fetch, axios
  • GraphQL: apollo-client, urql

Let me know if you need more customization!

Top comments (0)