Reputation: 23
So I keep getting this too many re-renders error after trying this code... I cant add data.results immediately on the state because it is undefined on the beggining.
import React, { useState } from 'react';
import { useParams } from 'react-router-dom';
import NotFound from './NotFound';
const Gender = ({ data }) => {
const { gender } = useParams();
const [people, setPeople] = useState([]);
if(data.results === undefined) return <div className='h-screen w-full flex items-center justify-center'>
<h1 className='font-bold text-3xl'>Loading...</h1>
</div>
setPeople(data.results)
if( gender === 'male' ) {
return null
} else if(gender === 'female') {
return null
} else {
return <NotFound />
}
};
export default Gender;
Upvotes: 0
Views: 471
Reputation: 219097
Because as part of rendering you are setting state. And setting state triggers a re-render. So the code will bounce between these two things indefinitely.
Since you're not actually using state here, there's no need to, well, use state here. The data you're using is passed to the component, so just rely on that. No need to also put it in a state value.
Something like this:
const Gender = ({ data }) => {
const { gender } = useParams();
if(data.results === undefined) return <div className='h-screen w-full flex items-center justify-center'>
<h1 className='font-bold text-3xl'>Loading...</h1>
</div>
if( gender === 'male' ) {
return null
} else if(gender === 'female') {
return null
} else {
return <NotFound />
}
};
Upvotes: 1