Home > Software engineering >  React update state filter object array
React update state filter object array

Time:05-27

I want to filter my object array, which I fetched from DB.

const [loadedCars, setLoadedCars] = useState();

useEffect(() => {
      setLoading(true);
      axios
        .get(process.env.REACT_APP_BACKEND_URL   "/cars/", {
          headers: {
            Authorization: "Bearer "   auth.token,
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          console.log(res.data.cars);
          setLoadedCars(res.data.cars);
          setLoading(false);
        });
  
  }, [auth.token]);

My code for Search likes that

let checker = (src, target) => target.every((v) => src.includes(v));
const searchHandler = (e) => {
    e.preventDefault();
    setDates(share.date_ranges);
    const filtered = loadedCars.filter((item) => !checker(item.dates, share.date_ranges));
    console.log(filtered);
    setLoadedCars(filtered)
  };

<Button onClick={searchHandler} className="search-btn" inverse>Search</Button>

Filter works just for one time. When I want to search a few times, it is not updated. And in the end my object array became empty.

How can I update my state? Thanks for help.

CodePudding user response:

This is happening because you are writing the results of your filter into loadedCars, then when you search again you use the same filtered array. Tip: You need two constants here, one for the db response and one that contains your filtered search.

CodePudding user response:

You need to use two state. First for all cars, second for filtered cars

const [loadedCars, setLoadedCars] = useState();
const [dbCars, setDbCars] = useState();


useEffect(() => {
      setLoading(true);
      axios
        .get(process.env.REACT_APP_BACKEND_URL   "/cars/", {
          headers: {
            Authorization: "Bearer "   auth.token,
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          console.log(res.data.cars);
          setLoadedCars(res.data.cars);          
          setDbCars(res.data.cars);
          setLoading(false);
        });
  
  }, [auth.token]);
  

let checker = (src, target) => target.every((v) => src.includes(v));
const searchHandler = (e) => {
    e.preventDefault();
    setDates(share.date_ranges);
    const filtered = dbCars.filter((item) => !checker(item.dates, share.date_ranges));
    console.log(filtered);
    setLoadedCars(filtered)
  };

<Button onClick={searchHandler} className="search-btn" inverse>Search</Button>

  • Related