F
F
fron3212021-11-14 13:56:35
React
fron321, 2021-11-14 13:56:35

How to fix Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. in my code?

An error appears Too many re-renders if I have a function called in catch. Basically, I'm simulating a search on the server, and if I get an error, then I want to perform a search on the client. In cath I call setData and insert filteredArray into it which does the lookup on the client. Here comes an error. Where am I writing the code wrong? how to fix?

const fruitData = [
  { item: "Apple", id: 1 },
  { item: "Blueberry", id: 2 },
  { item: "Grape", id: 3 },
  { item: "Banana", id: 4 }
];

const App: React.FC = () => {
  const [termInput, setTermInput] = useState<string>("")
  const [data, setData] = useState<any>(fruitData)
  const [loading, setLoading] = useState<boolean>(false)

const debouncedSearchTerm = useDebounce(termInput, 1000);

const visibleItems = (items:{item:string; id:number}[], termInput:string) => {
    if (termInput.length === 0) {
      setData(items)
    }
    return items.filter((item) => {
      return item.item.toLowerCase().includes(termInput.toLowerCase())
    })
  }
  
const filteredArray = visibleItems(fruitData, termInput)
  
  useEffect(() => {
    if (!debouncedSearchTerm) return;
      if (debouncedSearchTerm.length >= 0) {
        const mockServerSearch = (debouncedSearchTerm: string, fruitData: { item: string; id: number }[]) => {
          const isError = Math.round(Math.random())
          const visibleItemsServer = (items: { item: string; id: number }[], debouncedSearchTerm: string) => {
            if (debouncedSearchTerm.length === 0) {
              return items;
            }
            return items.filter((item) => {
              return item.item.toLowerCase().includes(debouncedSearchTerm.toLowerCase())
            })
          }
          const filteredArrayServer = visibleItemsServer(fruitData, debouncedSearchTerm)

          return new Promise((resolve, reject) => {
            setLoading(true)
            setTimeout(() => {
              if (isError) resolve(filteredArrayServer)
              else reject(new Error("Server search error"))
              setLoading(false)
            }, 2000)
          })
        }
        mockServerSearch(debouncedSearchTerm, fruitData)
          .then((filteredArrayServer) => {
            setData(filteredArrayServer)
          })
          .catch(() => {
            setData(filteredArray)
          })
      }
    
  }, [debouncedSearchTerm])

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question