heena shafique
heena shafique

Reputation: 1

Uncaught RangeError: Maximum call stack size exceeded in React application

Please help me. I am new in React and try to build an application to add contact in Local storage and delete contact. Following are the code of my App.js

import React, {useState, useEffect} from 'react'
import {uuid} from 'uuidv4'
import AddContact from './AddContact'
import ContactList from './ContactList'
import Header from './Header'

function App() {
  //useState Hooks in React
  const LOCAL_STORAGE_KEY = 'contacts'
  const [contacts, setContacts] = useState([])

  const addContactHandler = (contact) => {
    console.log(contacts)
    setContacts([...contacts, {id: uuid(), ...contact}])
  }

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id
    })
    setContacts(newContactList)
  }
  useEffect(() => {
    const retrieve_contact = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
    if (retrieve_contact) {
      setContacts(retrieve_contact)
    }
  }, [])

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts))
  }, [contacts])

  return (
    <div className="ui container">
      <Header />
      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} getContactId={removeContactHandler} />
    </div>
  )
}

export default App

I got the error Uncaught RangeError: Maximum call stack size exceeded.

Please help me how can i remove this error. Thank you!

Upvotes: 0

Views: 2313

Answers (1)

Kraken
Kraken

Reputation: 5860

You are updating react state inside useEffect, which triggers an infinite loop.

useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts))
  }, [contacts])

In short, you told useEffect to run when there are changes to contacts (by passing them into the dependency array as the second param to useEffect), causing it to run every time contacts changes, which triggers a state change to contacts, which triggers the useEffect loop again, infinitely. If the array was empty, it would run once on start.

For what you are trying to do here, it makes more sense to update your store when you add or remove contacts, i.e. call the storage functions from within your event handlers.

Here's a working code sandbox with the code you provided.

Upvotes: 1

Related Questions