Answer the question
In order to leave comments, you need to log in
Why is there an infinite loop in my code?
Why is there an infinite loop in my code?
The message appears: Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';
import Switcher from '../Switcher/Switcher';
import { contextArr } from '../../db';
import './Setting.scss';
export default function Component() {
const location = useLocation();
let [lang, setLang] = useState('en');
const chooseLang = (e) => {
setLang(e.target.checked ? (lang = 'ua') : (lang = 'en'));
};
window.location = location.pathname + '#' + lang;
for (let key in contextArr) {
let elem = document.querySelector('.lng-' + key);
if (elem) {
elem.innerHTML = contextArr[key][lang];
}
}
return (
<section id='setting'>
<Switcher
id='lang'
title='Language'
label_lt='English'
label_rt='Українська'
value={lang}
onClick={chooseLang}
/>
</section>
);
}
Answer the question
In order to leave comments, you need to log in
Apparently, the error pops up in some other, class component.
Here I see such a problem: window.location changes in rendering, which is completely wrong. This should happen in useEffect
useEffect(() => {
window.location = location.pathname + '#' + lang;
}, [location.pathname, lang]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question