Home > Back-end >  How to set back to original state React.js
How to set back to original state React.js

Time:07-26

This is my codeSandbox Code! https://codesandbox.io/s/bold-lederberg-d2h508?file=/src/Components/Products/Products.js

Once I click in "default" I want to have the items back to the original presentation please! But I can not do it

sorting by price is working but the default option is giving me problems


import React, { useState } from "react";
import Products from "./Components/Products/Products";
import SearchInput from "./Components/SearchInput/SearchInput";
import data from "./utils/data";

const App = () => {
  const [searchValue, setSearchValue] = useState("");
  const [productsInfo, setProductsInfo] = useState([]);

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

  const selectedChangeFilter = (e) => {
    const { value } = e.target;
    if (value === "sporting goods") {
      const sportingGoods = data.filter(
        (product) => product.category === "Sporting Goods"
      );
      setProductsInfo(sportingGoods);
    }
    if (value === "electronics") {
      const electronicsGoods = data.filter(
        (product) => product.category === "Electronics"
      );
      setProductsInfo(electronicsGoods);
    }
    if (value === "lowest price") {
      const lowestPriceGoods = data.sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = data.sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }
    if (value === "all") {
      setProductsInfo(data);
    }
  };

  const searchProducts = (products) => {
    if (searchValue.toLowerCase().trim() === "") {
      setProductsInfo(products);
    } else {
      const seekedItem = productsInfo.filter(
        (product) =>
          product.name.toLowerCase().trim().includes(searchValue) ||
          product.category.toLowerCase().trim().includes(searchValue)
      );
      setProductsInfo(seekedItem);
    }
  };

  return (
    <div>
      <SearchInput
        handleChange={handleChange}
        searchValue={searchValue}
        selectedChangeFilter={selectedChangeFilter}
      />
      <Products
        data={data}
        searchValue={searchValue}
        productsInfo={productsInfo}
        searchProducts={searchProducts}
      />
    </div>
  );
};
export default App;

I tried this one below but doesn't work

if (value === "all") {
const copiedData = [...data]
  setProductsInfo(copiedData);
}

CodePudding user response:

This is because while sorting you are sorting on your original data array. So the item ordering changes in it. You can copy your data into a seperate array and sort then as shown below.

Updated Codesandbox Link - https://codesandbox.io/s/fervent-napier-3rhvs4?file=/src/App.js

if (value === "lowest price") {
      const productsToSort = [...data]
      const lowestPriceGoods = productsToSort.sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const productsToSort = [...data]
      const highestPriceGoods = productsToSort.sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }

CodePudding user response:

I think it's because data.sort() change your javascript data object, and doesn't return a new array like filter.

Try by replacing data.sort() by [...data].sort()

const selectedChangeFilter = (e) => {
    const { value } = e.target;
    if (value === "sporting goods") {
      const sportingGoods = data.filter(
        (product) => product.category === "Sporting Goods"
      );
      setProductsInfo(sportingGoods);
    }
    if (value === "electronics") {
      const electronicsGoods = data.filter(
        (product) => product.category === "Electronics"
      );
      setProductsInfo(electronicsGoods);
    }
    if (value === "lowest price") {
      const lowestPriceGoods = [...data].sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = [...data].sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }
    if (value === "all") {
      setProductsInfo(data);
    }
  };

CodePudding user response:

This is happening because Array.sort() method is mutable. You are sorting the data array and returning the sorted value. This is a short example of what is happening.

const fruits = ["Melon", "Avocado", "Apple"];

console.log(fruits)  // ["Melon", "Avocado", "Apple"]

fruits.sort()

console.log(fruits)  // [ 'Apple', 'Avocado', 'Melon' ]

In order to avoid that in your code you can destructure the data array. This will create a new array pointing it to a different place in the memory.

  const selectedChangeFilter = (e) => {
    const { value } = e.target;
    // { . . . }
    
    if (value === "lowest price") {
      const lowestPriceGoods = [...data].sort((el1, el2) =>
        el1.price.localeCompare(el2.price, undefined, { numeric: true })
      );
      setProductsInfo([...lowestPriceGoods]);
    }
    if (value === "highest price") {
      const highestPriceGoods = [...data].sort((el1, el2) =>
        el2.price.localeCompare(el1.price, undefined, { numeric: true })
      );
      setProductsInfo([...highestPriceGoods]);
    }

  //  { . . . }

}
  • Related