Skip to content

Latest commit

 

History

History
168 lines (125 loc) · 3.75 KB

File metadata and controls

168 lines (125 loc) · 3.75 KB

Fetching Data Using fetch, axios, GraphQL, etc.

Using fetch() in React

The fetch() API is a built-in browser function that returns a Promise for making HTTP requests.

Key Points:

  • Native in modern browsers (no need to install).
  • Returns a Response object that must be converted (e.g., .json()).
  • Supports GET, POST, and other HTTP methods.
  • Requires manual error handling.
  • Doesn’t automatically cancel requests when the component unmounts.

Example – GET request:

import { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState([]);

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

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}

export default App;

Using Axios in React

Axios is a popular HTTP client library with extra features.

Key Points:

  • Must be installed: npm install axios
  • Automatically transforms JSON responses.
  • Has built-in error handling for non-2xx responses.
  • Supports request cancellation via tokens.
  • Can set base URLs and default headers globally.

Example – GET request:

import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then((response) => setData(response.data))
      .catch((error) => console.error(error));
  }, []);

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}

export default App;

Fetching Data with GraphQL in React

GraphQL is not an HTTP library but a query language for APIs. You send queries to a single endpoint, and the server returns exactly the data you requested.

Common tools in React:

  • Apollo Client
  • urql

Example – Using Apollo Client

1️⃣ Install dependencies:

npm install @apollo/client graphql

2️⃣ Setup Apollo provider:

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';

const client = new ApolloClient({
  uri: 'https://example.com/graphql',
  cache: new InMemoryCache(),
});

export default function Root() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}

3️⃣ Fetch data in a component:

import { useQuery, gql } from '@apollo/client';

const GET_POSTS = gql`
  query GetPosts {
    posts {
      id
      title
    }
  }
`;

function App() {
  const { loading, error, data } = useQuery(GET_POSTS);

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

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

export default App;

When to Use What

Feature fetch() Axios GraphQL
Built-in
Auto JSON parsing
Error handling Manual Built-in Built-in
Request cancellation AbortController Built-in Built-in
Best for Simple REST calls Complex REST APIs Flexible structured queries