0

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.

1
  • Please mark the answer that helped you as approved. Commented Jun 10, 2022 at 12:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.