I want to Prevent multiple request to an API
Tags: react, api, settimeout, webdev
Published: 2023-05-19 11:19:52

Here is my code , fix it with details. 
Thank you.


`import "../src/App.css";
import { Button } from "@mui/material";
import { TextField } from "@mui/material";
import { Grid } from "@mui/material";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import axios from "axios";
import { useState, useEffect } from "react";

export default function Design() {
  const [search, setSearch] = useState([]);
  const [record, setRecord] = useState("");

  const loadRecord = async () => {
    try {
      const res = await axios.get("https://fruityvice.com/api/fruit/all");
      setSearch(res.data);
    } catch (error) {
      console.error("Error loading records:", error);
    }
  };

  useEffect(() => {
    loadRecord();
  }, []);

  const searchRecord = async (search_term) => {
    try {
      if (search_term.length <= 3){
        // console.log(search_term)
        return;
      }
      const res = await axios.get(`https://fruityvice.com/api/fruit/${search_term}`);
      setSearch([res.data]);
    } catch (error) {
      console.error("Error searching record:", error);
      setSearch([]);
    }
  };

  const getTotalNutritions = (item) => {
    return Object.values(item.nutritions).reduce(
      (total, value) => total + Math.trunc(value),
      0
    );
  };

  return (
    <div>
      <h1 className="main--heading">Fruit Project</h1>
      <div className="main">
        <Grid className="grid" container>
          <Grid className="item" item>
            <TextField
              label="Search Fruit"
              variant="outlined"
              onChange={ search_term.length <=3 ? setTimeout(() => {
                  search_term(event.target.value)
              },3000) : (e) => searchRecord(e.target.value)}
            />
          </Grid>

          <Grid item className="outline--btn">
            <Button
              color="secondary"
              variant="contained"
              // onClick={searchRecord}
            >
              Search Fruit
            </Button>
          </Grid>
        </Grid>
      </div>
      <Table
        style={{ width: 400, margin: "auto" }}
        sx={{ minWidth: 650 }}
        aria-label="simple table"
      >
        <TableHead>
          <TableRow>
            <TableCell>Sr No</TableCell>
            <TableCell>Name</TableCell>
            <TableCell>Family</TableCell>
            <TableCell>Order</TableCell>
            <TableCell>Nutritions</TableCell>
            <TableCell>Genus</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {Array.isArray(search) && search.length > 0 ? (
            search.sort((a, b) => a.id - b.id).map((item) => (
              <TableRow
                key={item.id}
                sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
              >
                <TableCell component="th" scope="row">
                  {item.id}
                </TableCell>
                <TableCell>{item.name}</TableCell>
                <TableCell>{item.family}</TableCell>
                <TableCell>{item.order}</TableCell>
                <TableCell>{getTotalNutritions(item)}</TableCell>
                <TableCell>{item.genus}</TableCell>
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={2} align="center">
                {search.length === 0 ? "No data available" : "Loading..."}
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
}`

#react #react-js #js #javaScript