Home > OS >  How to filter array data in React js and update the data to useState
How to filter array data in React js and update the data to useState

Time:08-24

i really need help because i still learning about react js and data structure, i want ask about how to filtering spesific array data from redux and push to useState.

dataPortfo: [
{
  id: 0,
  title: "Retne Cms",
  link: "www.google.com",
  image: "/images/a1.png",
  category: "website",
},
{
  id: 1,
  title: "Jaramba",
  link: "",
  image: "/images/a1.png",
  category: "website",
},
{
  id: 2,
  title: "Atisiri Quiz Web",
  link: "",
  image: "/images/a2.png",
  category: "website",
},
{
  id: 3,
  title: "Retne Cms",
  link: "www.google.com",
  image: "/images/a1.png",
  category: "mobile",
},
{
  id: 4,
  title: "Retne Cms",
  link: "www.google.com",
  image: "/images/a1.png",
  category: "mobile",
},

],

aboove data from redux and i useSelector to get data from redux store.

const datePortfo = useSelector(selectPortfo);
const [kategori, setKategori] = useState("all");
const [filterData, setFilter] = useState([]);
  
  
  const checkKategori = () => {
    if (kategori === "website") {
      console.log("web");
      datePortfo.filter((data) => {
        if (data.category === "website") {
          console.log(data.category);
          setFilter([data]);
        }
      });
    }
    if (kategori === "mobile") {
      console.log("mob");
    }
    if (kategori === "all") {
      console.log("all");
    }

  };
  useEffect(() => {
    checkKategori();

    console.log(filterData);
    // console.log(kategori);
  }, [datePortfo,kategori]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

i want display spesific data based on category, when i try with my code and try to filter the data just display 1 data. pls help meee, thank you guys :) i'm still newbiee

CodePudding user response:

I think you should do that:

let filteredData = datePortfo;
if(kategori != "all")
  filteredData  = datePortfo.filter((data) =>  data.category === kategori);

setFilter(filteredData);

CodePudding user response:

  1. filter method creates a copy of the array, which you have to save in a variable. The function which you pass to filter is a predicate which has to return either true or false depending on whether the row is retained or not.

  2. The result of filter which you saved can be used in setFilteredData.

  • Related