A
A
Alexander2021-01-09 23:27:56
React
Alexander, 2021-01-09 23:27:56

How to remove dependency array in useEffect, useCallback?

Can you please tell me how to remove this warning?

5ffa10e8ebe1e519548360.png

import React from 'react'
import { Categories, SortPopup, PizzaItem, Preloader } from '../components'
import { useDispatch, useSelector } from 'react-redux'
import { setCategory, setSortBy } from '../redux/actions/filters'
import { fetchPizzas } from '../redux/actions/pizzas'
import { addPizzaToCart } from '../redux/actions/cart'

const categoryNames = ['Мясные', 'Вегетерианская', 'Гриль', 'Острые', 'Закрытые']
const sortItems = [
  { name: 'популярности', type: 'popular', order: 'desc' },
  { name: 'цене', type: 'price', order: 'desc' },
  { name: 'алфавит', type: 'name', order: 'asc' },
]

function Home() {
  const dispatch = useDispatch()
  const items = useSelector(({ pizzas }) => pizzas.items)
  const cartItems = useSelector(({ cart }) => cart.items)
  const isLoading = useSelector(({ pizzas }) => pizzas.isLoading)
  const { category, sortBy } = useSelector(({ filters }) => filters)

  React.useEffect(() => {
    dispatch(fetchPizzas(sortBy, category))
  }, [category, sortBy])

  const onSelectCategory = React.useCallback((index) => {
    dispatch(setCategory(index))
  }, [])

  const onSelectSortType = React.useCallback((type) => {
    dispatch(setSortBy(type))
  }, [])

  const handleAddPizzaToCart = (obj) => {
    dispatch(addPizzaToCart(obj))
  }

  return (
    <div className='container'>
      <div className='content__top'>
        <Categories activeItem={category} onClickCategory={onSelectCategory} items={categoryNames} />
        <SortPopup activeSortType={sortBy.type} onClickSortType={onSelectSortType} items={sortItems} />
      </div>
      <h2 className='content__title'>Все пиццы</h2>
      <div className='content__items'>
        {isLoading
          ? items.map((obj) => (
              <PizzaItem
                {...obj}
                onClickAddPizza={handleAddPizzaToCart}
                addedCount={cartItems[obj.id] && cartItems[obj.id].items.length}
                key={obj.id}
              />
            ))
          : Array(12)
              .fill(0)
              .map((_, index) => <Preloader key={index} />)}
      </div>
    </div>
  )
}

export default Home

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2021-01-09
@axrising

Add dispatch to arrays to other dependencies as warning advises

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question