React : Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

I’m using useEffects still getting this error

const Event = () => {

    const [eventType,seteventType] = useState('ALLEVENTS');
    const [filteredEvents,setfilteredEvents] = useState();
    const [events,setevents] = useState();

    // const handelChange = (e)=>{
    //     seteventType(e.target.value)
    // }

    useEffect(() => {
    const sendRequest = async () => {
        try {
          const response = await fetch('http://localhost:5000/api/events');
    
          const responseData = await response.json();
        console.log(responseData)
          if (!response.ok) {
            console.log("error")
          }
        setevents(responseData)
    
        } catch (err) {
          console.log(err);
        }
      };
      sendRequest();
    },[]);
  
    // const currentEventType = this.state.eventType;


    if(eventType === 'VERIFIED'){
        filteredEvents = events.filter(event =>event.verified === true);
    }
    else if(eventType === 'UNVERIFIED'){
        filteredEvents = events.filter(event =>event.verified === false);
    }
    else{
        // console.log(events)
        setfilteredEvents(events);
        // console.log("hhiiiiiiiiiiii")
    }


    return (
        <React.Fragment>
            <Navbar/>
            {/* handelChange={handelChange} */}
            <Selector />
            <div>
            <EventList events={events} />
            </div>
        </React.Fragment>
    )
}

export default Event

What happens if you comment out setfilteredEvents(events) in else?

@Advitya-sharma I noticed you reassign to filteredEvents. Are you supposed to use setfilteredEvents? for put new data into the state?
and use filteredEvents for render?

1 Like

it works then but I’m having same issue when I’m using other if satements

I was just testing with setfilterevent its not working with setevent too

modified the code a bit

import EventList from '../components/EventList'
import React, { Component ,useEffect,useState} from 'react'
import Selector from '../components/Selector';
import Navbar from '../../shared/components/navigation/Navbar';

// export class Event extends Component {

// constructor(props) {
//     super(props);
//     this.state = {
//         eventType:'ALLEVENTS',
//         events:{},
//     };
//     this.handelChange = this.handelChange.bind(this)
// }
//     handelChange = (e)=>{
//         this.setState({eventType:e.target.value})
//     }

//     filteredEvents=[]

//     render() {

//             const sendRequest = async () => {
//               try {
//                 const response = await fetch('http://localhost:5000/api/events');
          
//                 const responseData = await response.json();
//                 this.setState({events:responseData})

//                 if (!response.ok) {
//                   console.log("error")
//                 }
          
//               } catch (err) {
//                 console.log(err);
//               }
//             };

//             sendRequest();
        
//     const currentEventType = this.state.eventType;


//     if(currentEventType === 'VERIFIED'){
//         this.filteredEvents = this.state.events.filter(event =>event.verified === true);
//     }
//     else if(currentEventType === 'UNVERIFIED'){
//         this.filteredEvents = this.state.events.filter(event =>event.verified === false);
//     }
//     else{
//         this.filteredEvents = this.state.events;
//         console.log(this.state.events)
//         console.log("hhiiiiiiiiiiii")
//     }

//     return (
//         <React.Fragment>
//             <Navbar/>
//             <Selector handelChange={this.handelChange}/>
//             <div>
//             <EventList events={this.state.events} />
//             </div>
//         </React.Fragment>
//         )
//     }
// }

// export default Event

// import React from 'react'

const Event = () => {

    const [eventType,seteventType] = useState('ALLEVENTS');
    const [filteredEvents,setfilteredEvents] = useState();
    const [events,setevents] = useState([]);
    const [isLoading,setisLoading] = useState(true);

    const handelChange = (e)=>{
        console.log(e.target.value)
        seteventType(e.target.value)
    }

    useEffect(() => {
    const sendRequest = async () => {
        try {
          const response = await fetch('http://localhost:5000/api/events');
    
          const responseData = await response.json();
          
          console.log(responseData)
          console.log("responseData")

          if (!response.ok) {
            console.log("error")
          }
        console.log(responseData)
        setevents(responseData)
        setisLoading(false)
    
        } catch (err) {
          console.log("errrrrrroooooooorrrrrrr");
          console.log(err);
        }
      };
      sendRequest();
    },[]);
  
    // const currentEventType = this.state.eventType;
    if(isLoading === false){
        if(eventType === 'VERIFIED'){
            console.log("verified")
            console.log(events['events'])
            setevents(Array.isArray(events['events']) ? events['events'].filter(event =>event.verified === true) : []);
        }
}
    else if(eventType === 'UNVERIFIED'){
        events.filter(event =>event.verified === false);
    }
    else{
        console.log(events)
        // setfilteredEvents(events);
    }


    return (
        <React.Fragment>
            <Navbar/>
           
            <Selector  handelChange={handelChange}/>
            <div>
                {!isLoading &&
            <EventList events={events} />}
            </div>
        </React.Fragment>
    )
}

export default Event

here

when I select verified from dropdown this code works
its giving me

Too many re-renders. React limits the number of renders to prevent an infinite loop.

 if(isLoading === false){
        if(eventType === 'VERIFIED'){
            console.log("verified")
            console.log(events['events'])
            setevents(Array.isArray(events['events']) ? events['events'].filter(event =>event.verified === true) : []);
        }
}

The problem is that each time you set state the component is re-rendered. And if you set state in the body of the component (or in render) you’ll have an infinite loop.

ooh I’ve been searching continuously but cannot find solution for this do you have any idea on how I can go on solving this

Just looking quickly and not deeply, what about using useEffect watching for changes in _ eventType_?

Don’t you need to set the eventType back so you do not hit the same if statement over and over again?

isLoading is false, eventType is VERIFIED, you call setevents the component re-renders.

isLoading is still false, eventType is still VERIFIED, you call setevents the component re-renders. And so on.

Or maybe I just didn’t read that correctly?

You should put your if...else statement inside sendRequest and set events together with filtered events. Then in handleChange you probably will have to repeat the same if...else statement.
Then you can extract this filtering logic into separate function to avoid duplication.

Same issue with me
function App() {

const [loading, setLoading] = useState(true);

const [tours, setTours] = useState();

useEffect(() => {

Axios.get(url)

.then(res =>{

const data = res.data;

setLoading(false);

setTours(data);

})

.catch(err =>{

console.log(err);

});

},)

if(loading){

return(

<main>

  <Loading />

</main>

)

}

return (

<main>

    <Tours tours= {tours} />

</main>

)

}

export default App

This is a old thread. It is better to make a new topic for your issue instead of necro-ing an old thread and hijacking it. I’m going to lock this thread. Thanks for understanding.

1 Like