useeffect database example in typescript

index.ts
import { useEffect, useState } from "react";
import { fetchDataFromDatabase } from "./api"; // example API function to fetch data from the database

const Component = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await fetchDataFromDatabase();
        setData(result);
      } catch (error) {
        console.error("Error fetching data from database: ", error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};
623 chars
28 lines

In the code snippet above:

  • We import useEffect and useState from react.
  • We define a functional component Component.
  • Inside the component, we define a state variable data and a function setData using useState which will hold the fetched data from the database.
  • We use useEffect to fetch data from the database when the component mounts.
  • We call an async function fetchData within the useEffect to fetch data asynchronously from the database using an imaginary fetchDataFromDatabase API function.
  • When the data is fetched successfully, we update the state variable data using setData.
  • We display the fetched data in the component.

Remember to replace fetchDataFromDatabase and the sample data structure with actual functions and model types relevant to your database implementation.

related categories

gistlibby LogSnag