Home > Back-end >  Trying to filter data that I fetched with fetch API in ReactJs
Trying to filter data that I fetched with fetch API in ReactJs

Time:10-07

I'd like to filter the data fetched from the api by names that include the letter "A" and then place only the employee names in a div. I've been trying for a while but can't seem to get it to work. How can I achieve this?

import React, { useState, useEffect } from "react";

export default function App() {
  const [data, setData] = useState([]);
  const [input, setInput] = useState("");
  const [suggestions, setSuggestions] = useState([]);

  useEffect(() => {
    fetch("https://dummy.restapiexample.com/api/v1/employees")
      .then((response) => response.json())
      .then((result) => setData(result.data));
  }, []);

  const info = data.map((employee) => {
    return <div> {employee.employee_name} </div>;
  });

  const handleChange = (e) => {
    setInput(e.target.value);
  };

  return (
    <div className="App">
      <form>
        {" "}
        Enter your Search:
        <input type="text" onChange={handleChange}></input>
      </form>
      <div className="suggestions-div">{info}</div>
    </div>
  );
}

CodePudding user response:

If you're wanting to filter specifically by the letter "A", then you could accomplish that like this:

const info = data
  .filter((employee) =>
    employee.employee_name.includes("A"))
  .map((employee, index) => (
    <div key={index}>{employee.employee_name}</div>
  ));

However, it looks like your intention is to filter by the value entered into input. If that's the case, I would perform a case-insensitive filter on data by the value of input like this:

const info = data
  .filter((employee) =>
    employee.employee_name.toLowerCase().includes(input.toLowerCase()))
  .map((employee, index) => (
    <div key={index}>{employee.employee_name}</div>
  ));

Note: You also need to add a key to the top-level element inside your .map(). That could be the unique ID of the employee object or simply the index of the map as in my examples above.

CodePudding user response:

You can filter and set state as, This will filter out and set the data state using setData. CODESANDBOX

setData(result.data.filter((str) => str.employee_name.includes("A")))

CodePudding user response:

If you want to filter the data based on your input's value, one way to do it is the following.

  const filteredData = useMemo(() => {
    if (!data) return [];
    if (!input) return data;

    return data.filter((employee) =>
      employee.employee_name.toLowerCase().includes(input.toLowerCase())
    );
  }, [data, input]);

  const info = filteredData.map((employee) => {
    return <div> {employee.employee_name} </div>;
  });
  • Related