Infinite loop in ComponentDidUpdate

I need to translate from Russian to Spanish and change some info in my React state. To achieve it I wrote a function called "translateHelper" that looks like this:

translateHelper() {
        let type = this.state.tipo; 
        switch(type) { //translating
            case 'Проектор':
                type = 'Proyector';
                break;
            case 'Манифестор':
                type = 'Manifestador';
                break;
            case 'Генератор':
                type = 'Generador';
                break;
            case 'Манифестирующий генератор':
                type = 'Generador Manifestante';
                break;
            case 'Рефлектор':
                type = 'Reflector';
                break;        
        }
        if (this.state.sexo === 'female' && type !== 'Generador Manifestante') { //changes depending on sex
            type = type + 'a'
        }
        else if (this.state.sexo === 'female' && type === 'Generador Manifestante') {
            type = 'Generadora Manifestante'
        }
        this.setState({ //updating state
            tipo: type
        })
    }

Problem appears when I try to call this function from ComponentDidUpdate. It throws error saying: "Maximum update depth exceeded". As far as I understand this happens bc of the infinite loop in ComponentDidUpdate. But I don't understand where it is as I set the break condition that looks like this:

componentDidUpdate(prevProps, prevState) {
        if (prevState.tipo !== this.state.tipo) { //my condition
            this.translateHelper();
        }
    }

How can I fix it?

Upvotes: 0

Views: 36

Answers (1)

marcos
marcos

Reputation: 4510

Indeed is caused in your componentDidUpdate method, when translateHelper is called, it modifies the state, causing it to be called again, and so on, since there is no stop mechanism. The prevState.tipo !== this.state.tipo check is not doing anything, u should check if this.state.tipo is not in Spanish, and that's when u should only run translateHelper. Because u keep feeding the results of your first translation:

Проектор -> Proyector -> Proyectora -> Proyectoraa -> Proyectoraaa

Edit:

Since the number of words finite, what u can do is check if the word was already translated, if it was translated, u don't need to translate again right?, for example:

const translatedWords = ['Proyector', 'Proyectora', ... ]

componentDidUpdate(prevProps, prevState) {
        const isTranslated = translatedWords.includes(this.state.tipo);
        if (!isTranslated) { 
            this.translateHelper();
        }
    }

Upvotes: 1

Related Questions