Menu

Event Handling & Data Fetching

Event Handling & Data Fetching

Event handling is the process of responding to user actions such as typing (searching), clicking, or form submissions. In React, these events trigger functions that control how the application behaves, making the UI more interactive.

Data fetching is the process of retrieving data from sources such as APIs, databases, local JSON files, browser storage, or third-party services. It allows the application to access the data and use it in the required part of the UI.

const [search, setSearch] = useState("");
const [recipes, setRecipes] = useState([]);
const [loading, setLoading] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [selectedRecipe, setSelectedRecipe] = useState(null);

-----------------

<div className="search-bar-container w-full md:w-[90%] lg:w-[80%] xl:w-[50%] relative flex items-center">
          <input
            type="search"
            name="search-recipe"
            id="search-recipe"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                fetchRecipes();
}
}}
            className="w-full text-base md:text-lg py-2 px-3"
            placeholder="Search the recipe....."
          />
          <FontAwesomeIcon
            icon={faSistrix}
            className="search-icon text-lg md:text-2xl absolute right-10 cursor-pointer"
            onClick={fetchRecipes}
          />
          {search && (
            <FontAwesomeIcon
              icon={faXmark}
              className="clear-icon text-base md:text-lg absolute right-2 cursor-pointer"
              onClick={() => {
                setSearch("");
}}
            />
)}
</div>

-----------------

const fetchRecipes = async () => {
    if (!search) return;
    setHasSearched(true);
    setLoading(true);
    try {
      const response = await fetch(
        `https://tasty.p.rapidapi.com/recipes/list?from=0&size=10&q=${search}`,
{
          method: "GET",
          headers: {
            "X-RapidAPI-Key":
              "7a3a553868mshd9dc2d1e96281a6p1ce958jsn48611636ad48",
            "X-RapidAPI-Host": "tasty.p.rapidapi.com",
},
},
);
      const data = await response.json();
      console.log("API Response:", data);
      setRecipes(data.results || []);
} catch (error) {
      console.error("Error fetching recipes:", error);
} finally {
      setLoading(false);
}
};

Explanation:

A. Event Handling

  • Event handling here controls what happens when the user interacts with the search bar.

  • When the user types, the onChange event runs and updates the search state with the entered value.

  • When the user presses the Enter key (onKeyDown) or clicks the search icon, the fetchRecipes function starts searching.

  • The clear icon appears only when there is text, and clicking it resets the input.

  • So basically, events capture user actions (typing, pressing Enter, clicking) and trigger the appropriate functions to make the app respond instantly.

B. Data Fetching

Data fetching happens inside the fetchRecipes function. When it runs, it first checks if the search input is empty; if so, it stops. Then setHasSearched(true) is used to mark that a search has been performed, which helps in showing results or messages later.

After that, loading is set to true while the API request is being sent using fetch with the search keyword.

When the response comes back, response.json() converts the raw API response into usable JavaScript data (JSON format).

Then setRecipes(data.results || []) stores the recipe data in state—if data.If results exist, it uses them; otherwise, it sets an empty array to avoid errors. If any error occurs, it is handled in the catch block, and finally, loading is set back to false once everything is done.

P.S - To use this API, an API key is required. Here, the Tasty API from RapidAPI needs a valid key to fetch recipe data.