DEV Community

Ogasawara Kakeru
Ogasawara Kakeru

Posted on • Edited on

React Basics~useEffect/ Data Fetching~

・src/components/Select.tsx

import { useEffect, useState } from "react";
import { fetchBio } from "./fetchBio";

const Select = () => {
  const [person, setPerson] = useState<string>("Shincode");
  const [bio, setBio] = useState<string | null>(null);

  useEffect(() => {
    let ignore = false;
    const startFetching = async () => {
      const response = await fetchBio(person);

      if (!ignore) {
        setBio(response);
      }
    };
    startFetching();
    return () => {
      ignore = true;
    };
  }, [person]);

  return (
    <div>
      <select onChange={(e) => setPerson(e.target.value)} value={person}>
        <option value="ShinCode">ShinCode</option>
        <option value="TestUser">TestUser</option>
        <option value="SampleUser">SampleUser</option>
      </select>

      <hr />

      <p className="text-black">{bio ?? "Loading..."}</p>
    </div>
  );
};

export default Select;
Enter fullscreen mode Exit fullscreen mode

・This component displays a select box that fetches a bio message in the useEffect when you change the option.

・When the option is changed, the p element displays the selected option value with the bio message.

・In the useEffect, we fetch the bio message when the person state is changed.

・Before the person state is changed, the cleanup function is called to set the ignore value to true and prevent the fetchBio function response from being placed into the setBio function.

・src/components/fetchBio.ts

export async function fetchBio(person: string) {
  await new Promise((resolve) => setTimeout(resolve, 1000));

  const bio = `This is a ${person}'s bio`;
  return bio;
}
Enter fullscreen mode Exit fullscreen mode

・This file returns a message like This is a ${person}'s bio.

・The person is a valuable recieved as an argument

・src/App.tsx

import "./App.css";
import Select from "./lessons/Lesson2/Lesson2_2/Select";

function App() {
  return <Select />;
}

export default App;

Enter fullscreen mode Exit fullscreen mode

・This component displays a Select component.

Image description

Top comments (0)