Fetch data

2 snippets across 2 stacks - React, SQL

Also written as fetch all data

REReact

Fetching Data

RE · useEffect
Syntax
useEffect(() => {
  let ignore = false;
  async function load() {
    const data = await fetchData();
    if (!ignore) setState(data);
  }
  load();
  return () => { ignore = true; };
}, [deps]);
Example
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let ignore = false;
    setLoading(true);

    async function loadUser() {
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      if (!ignore) {
        setUser(data);
        setLoading(false);
      }
    }
    loadUser();

    return () => { ignore = true; };
  }, [userId]);

  if (loading) return <p>Loading...</p>;
  return <div>{user.name}</div>;
}

Note The ignore flag prevents setting state on an unmounted component or after a stale request. In React 19, consider using the use() hook with Suspense for data fetching instead of this pattern.

SQLSQL

SELECT All Columns

SQL · Basic Queries
Syntax
SELECT * FROM table_name;
Example
SELECT * FROM users;
Output
-- Returns all columns and rows from the users table

Note Avoid SELECT * in production code. Always specify columns to reduce data transfer and prevent breakage when table schema changes.

Frequently asked questions

How do you fetch data?
This task is covered in 2 stacks on this page: React, SQL. The "Fetching Data" snippet in React uses `useEffect(() => {`.
Which code does the React example use?
The "Fetching Data" snippet uses `useEffect(() => {`, from the useEffect section of the React cheat sheet.
Which stacks cover "fetch data" on this page?
React, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Fetching Data": The ignore flag prevents setting state on an unmounted component or after a stale request. In React 19, consider using the use() hook with Suspense for data fetching instead of this pattern.