Home > Net >  Too many re-renders and code not refreshing
Too many re-renders and code not refreshing

Time:04-18

so I am getting the error too many re-renders when trying to update the state of an array.

I declare an array called sampleFriends, made up of objects with fields "name", "location", and "picture" (each element of the array looks similar to: {name: 'John', location: 'Boston', picture: TestImage}).

Then I use useState as follows:

  const [searchQuery, setSearchQuery] = useState('')
  const [friendMatches, setFriendMatches] = useState(sampleFriends)

I also have a TextInput component:

<TextInput
      value={searchQuery}
      onChangeText={setSearchQuery}
      onChange={search()}
      placeholder="Search Contacts"
      keyboardType="default"
    />

And a search() function that looks like this:

  const search = () => {
    const coincidences = sampleFriends.filter(({ name }) => name.includes(searchQuery))
    setFriendMatches(coincidences)
  }

I want to render the users whose name matches searchQuery, and coincidences gives me the users, but I can't use setFriendMatches to update the matchesState (which is what I'd like to render). Hope it makes sense and thanks for your help!!

UPDATE: Some responses told me to change onChange={search()} to onChange={search} and that eliminated the error. However, now search never runs.

CodePudding user response:

In the onChange event, just mention the function name like this onChange={search} or if you need to put some parameters, call it within a function as below.

This is what your final code block should look like.

<TextInput
      value={searchQuery}
      onChangeText={setSearchQuery}
      onChange={() => search()}
      placeholder="Search Contacts"
      keyboardType="default"
    />

Let me know if it works

CodePudding user response:

Replace your code with this :

  <TextInput
  value={searchQuery}
  onChangeText={setSearchQuery}
  onChange={search}    // <-  This One is Important
  placeholder="Search Contacts"
  keyboardType="default"
 />

CodePudding user response:

Change Line 4 in TextInput from onChange={search()} to onChange={search}.

By calling the function you are triggering an infinite re-render at each re-render.

There are probably other issues since it's unlikely that your component wants a double onChange event listener, I made a simple demo to show you how to possibly manage these scenarios in a cleaner way: https://stackblitz.com/edit/react-eijegp

  • Related