Home > Blockchain >  Why I have a loop in my react application?
Why I have a loop in my react application?

Time:04-25

I'm learning React and I'm making my application to test the library but I've got a strange loop and I don't figure out where does it come from.

My code :

import React, {useEffect, useState} from 'react';
import Navigation from "../components/Navigation";
import axios from "axios";
import Card from "../components/Card";
import {randomNumber} from "../components/_helper";

const Home = () => { 
    console.log('coucou')

    const [randomCharacters, setRandomCharacters] = useState([]);
    const [totalCharacters, setTotalCharacters] = useState('');
    const [randomNumbers, setRandomNumbers] = useState('');


    useEffect(() => {
        axios.get('https://rickandmortyapi.com/api/character')
            .then((response) => {
                setTotalCharacters(response.data.info.count)
            })
    })

    useEffect(() =>{
        axios.get('https://rickandmortyapi.com/api/character/1,23,45,654,21,12')
            .then((response) => {
                response.data.map(() => (
                    setRandomCharacters(response.data)
                ))
            })
    })
    return (
        <div>
            <Navigation/>
            {randomCharacters.map( (character) => (
                <Card key={character.id} character={character}/>
            ))}
        </div>
    );
};

export default Home;

As you can see, I did a console.log at the beginning of my code and I have no loop writing (for, foreach) but this is what happen in the console :

result from the console

I don't understand this behavior, someone to explain where I did wrong ?

CodePudding user response:

Your 2 useEffects run every time when re-render occurs.

In your useEffect, you update state variables randomCharacters and totalCharacters. Then re-render occurs whenever your APIs return different data because of these state updates.

So your app loops infinitely.

At least you need to add one more dependency. But in your case, you can pass empty dependency [] for one time API call.

Here is a tip from React official document. If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

Code should look like the following:

    useEffect(() => {
        axios.get('https://rickandmortyapi.com/api/character')
            .then((response) => {
                setTotalCharacters(response.data.info.count)
            })
    }, [])

useEffect(() =>{
        
    axios.get('https://rickandmortyapi.com/api/character/1,23,45,654,21,12')
            .then((response) => {
                response.data.map(() => (
                    setRandomCharacters(response.data)
                ))
            })
    }, [])
  • Related