0
votes

Iam a new to react and recently i just have just been practicing react by making a simple shopping cart functionality

this is part of the code i get the error from:

const MainShop = () => {
  const [products, setProducts] = useState([]);
  const [category, setCategory] = useState('');
  const [sort, setSort] = useState('');
  const [filteredProducts, setFilteredProducts] = useState([]);

  useEffect(() => {
    const fetchItems = async () => {
      const data = await fetch('https://fakestoreapi.com/products');
      const items = await data.json();
      console.log(items);
      setProducts(items);
      setFilteredProducts(products);
    };
    fetchItems();
  }, []);

the error says: Line 42:6: React Hook useEffect has a missing dependency: 'products'. Either include it or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setFilteredProducts' needs the current value of 'products' react-hooks/exhaustive-deps

how do i solve this problem?

1
It depends on how often you want the useEffect callback to run.Drew Reese
setFilteredProducts(products) - but what are we trying to do here . should this be something like setFilteredProducts(items.filter(based on some condition))Shyam

1 Answers

1
votes

Basically, you should first learn what is useEffect Dependency Array. Also in your question define the states you are using and where are you getting products what is the difference with fetched items. If they are different is it necessary to keep them in the same useEffect hook? Note that you can have several effect hooks in one component with different dependencies array

But as a fast hack, if you want the fetch to be triggered only once when the component mounts, disable the dependency error like below.

useEffect(() => {
    const fetchItems = async () => {
      const data = await fetch('https://fakestoreapi.com/products');
      const items = await data.json();
      console.log(items);
      setProducts(items);
      setFilteredProducts(products);
    };
    fetchItems();
   // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

If according to filters the fetch should be triggered again

useEffect(() => {
    const fetchItems = async () => {
      const data = await fetch(`https://fakestoreapi.com/products?filter=${filters}`);
      const items = await data.json();
      console.log(items);
      setProducts(items);
      setFilteredProducts(products);
    };
    fetchItems();
  }, [filters]);