My react function component keeps re-rendering itself over and over until the browser crashes.
The only solution i could find was entering [] with my constant at the end of useEffect().
function getNestedObject(nestedObj, pathArr) {
return pathArr.reduce(
(obj, key) => (obj && obj[key] !== "undefined" ? obj[key] : undefined),
nestedObj
);
}
function Genres() {
const [genreList, setgenreList] = useState(0);
useEffect(() => {
let results = "";
axios({
url: "https://api.themoviedb.org/3/genre/movie/list?",
method: "GET",
responseType: "json",
params: {
api_key: "00000000000",
language: "en-US"
}
}).then(result => (results = result.data.genres));
let a = [];
for (let i = 0; i < 10; i++) {
let name = getNestedObject(results, [i, "name"]);
a.push(name);
}
setgenreList(a);
console.log(genreList);
}, [genreList]);
return <div>test</div>;
}
I have also tried it without the useEffect which gives the same looping result.
I have <Genres /> down in the render.
Its happening because of you are calling
setgenreList(a);
at useffect , genreList change its state, UseEffect run again
when you are writing
useEffect(() => {}, [genreList])
then it will be called everytime when you call its setter setgenreList
you may write
useEffect(() => {
//code here
}, [])
Actually, you are generating an empty array every time and updating the state with a newly generated array every time, hence useEffect loops infinitely (check [] === []). Also you have an obvious error in the code: the state update doesn't depend on axios result at all, since you don't wait for response results ("then" block is executed after setgenreList(a)). Use state update inside "then" function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With