Saturday, 15 August 2026

Tanstack query vs React Fetch -Axios

import { useQuery } from "@tanstack/react-query";

function Users() {
  const { data, isLoading, isError, error } = useQuery({
    queryKey: ["users"],
    queryFn: async () => {
      const res = await fetch("/api/users");
      if (!res.ok) {
        throw new Error("Failed to fetch users");
      }
      return res.json();
    },
  });

  if (isLoading) return <p>Loading...</p>;

  if (isError) {
    return <p>{error.message}</p>;
  }

  return (
    <ul>
      {data.map((user: any) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

//Plain fetch 

useEffect(() => {
  fetch("/api/users")
    .then(...)
}, []);

import { useState, useEffect } from 'react';
function UserList() {
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  useEffect(() => {
    setIsLoading(true);
    fetch('https://api.example.com/users')
      .then((res) => {
        if (!res.ok) throw new Error('Failed to fetch');
        return res.json();
      })
      .then((data) => {
        setUsers(data);
        setIsLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setIsLoading(false);
      });
  }, []);
  if (isLoading) return 

Loading...

; if (error) return

Error: {error}

; return (
    {users.map((user) => (
  • {user.name}
  • ))}
); }

No comments:

Post a Comment

Tanstack query vs React Fetch -Axios

import { useQuery } from "@tanstack/react-query"; function Users() { const { data, isLoading, isError, error } = useQuery({ ...