1

I have an issue with sort and filter of data as I am using same method setData for productsort and filterBy but the sorted data getting updated on dom when I trigger change in filterBy component first then only it showing the sorted data

export default ({
  data = [],
  filterBy,
  productSort,
}: Iproduct) => {
  const [_data, setData] = useState<any>(data)

  useEffect(() => {
    setData(
      data.sort((a: Obj, b: Obj) => {
        if (a.name < b.name) {
          return -1
        }
      })
    )
  }, [data])

  return (
    <>
      <div className="sortMenu">
        {productSort &&
          ComponentsBuilder({
            ...productSort,
            onChange: (name: string, value: string) => {
              setData(
                data.sort((a: Obj, b: Obj) => {
                  if (a.name > b.name) {
                    return -1
                  }
                })
              )
            },
          })}
        {filterBy &&
          ComponentsBuilder({
            ...filterBy,
            onChange: (event: ChangeEvent<any>) => {
              const { value } = event.target
              setData(
                data.filter(({ name }: any) =>
                  name.toLocaleLowerCase().includes(value.toLocaleLowerCase())
                )
              )
            },
          })}
      </div>
      <List
        className="products-cards-list"
        data={_data}
        grid={grid}
      />
    </>
  )
}
RTM
  • 39
  • 4
  • Not a duplicate those are different please read description fully...before making duplicate – RTM May 17 '21 at 15:41
  • It is the same question. You are missing a key element. When you change the `filter`, you will need to store it in state, rather than applying directly. The sort and filter should happen on every state change. There are many ways to do this, but the duplicate link explains it in more detail. – ChrisG May 17 '21 at 15:43

0 Answers0