How to Resolve Infinite Request Loop React.js?

Asked

Viewed 141 times

2

En route GET that upload backend image on useState that this in a component of the React is making infinite request to my backend

component code:

    
import React,{useState,useEffect} from 'react'
import{FiTrash2} from 'react-icons/fi'
import {Link} from  'react-router-dom'
 
import api from '../../../services/api';
import './stylesimp.css' 

function MPetImagem(props){
    async function deleteImg(imagem){
        api.delete('imagem',{
            headers:{
                name:imagem.name,
                id:imagem.id
            }
        });
        setImagem(imagens.filter(incident=> incident.id !== imagem.id))

    }
    const [imagens,setImagem] = useState([]);

    const {pet} = props;
   
    useEffect(()=>{
        api.get('imagem',{
            headers:{
                authorization:pet.id,
            }
        }).then(response => setImagem(response.data))
    })

    return(
        <ul>
            {imagens.slice(0,3).map(imagem =>(
                <li key={imagem.id}>
                    <Link onClick={()=>deleteImg(imagem)}><FiTrash2></FiTrash2></Link>
                    <img src={imagem.url} alt="imagem pet"></img>
                </li>
            ))}
        </ul>
           
        
    )
}
export default MPetImagem;

Screenshot do código do componente 1 Screenshot do código do componente 2
Screenshots of component code. Click on the image to view in its original size

Where the component is called

import React,{useEffect,useState} from 'react'
import {Link,useHistory} from  'react-router-dom'
import{FiEdit,FiImage, FiTrash2} from 'react-icons/fi'
import api from '../../services/api'


import Logo from '../../assests/images.png'

import ImgPet from '../componente/imgmeuspets'

import cat from '../../assests/rascuepetlogo.png'



import './stylesmp.css'

export default function PetsPerdidos(){
    
    const [pets,setPets]= useState([]);
    const history = useHistory();

    const dono_id = localStorage.getItem('dono_id');
  
useEffect(()=>{
        api.get('meuspets',{
            headers:{
                authorization:dono_id,
            }

        }).then(response=>{setPets(response.data)})
        localStorage.removeItem('pet_id');
    },[dono_id]);

    function Position(id,local){
        localStorage.setItem('pet_id',id);

        history.push(`/${local}`)

        
    }
    
    async function DeletePet(id){
        try{ 
         await api.delete(`pets/${id}`,{
             headers:{
                 authorization:dono_id
             }
         });
         setPets(pets.filter(pet=> pet.id!== id))

       

       
    }catch(err){
        alert(err);
    }

    }
  

 

    
    return (
    <div className="meuspets-container">

        
         <header>
             
             <img src={cat} alt="logo"></img>
             <Link class="button" to="/petsperdidos">Home</Link> 
             <Link class="button" to="/newpet">Cadastrar Pet</Link>
               
                
               

                
        </header>
       
        <h1>Meus Pets</h1>
        <ul>
            {pets.map(pet=>(
            <li  key={pet.id}>
                <h3>{pet.name}</h3>
            
            <Link className="editar" onClick={()=>Position(pet.id,'editar')}><FiEdit/> Editar pet</Link>
            <Link className="editar" onClick={()=>Position(pet.id,'adicionar-imagem')}><FiImage/> Adicionar imagem</Link>
            <button className="button-delete" onClick={()=>DeletePet(pet.id)}><FiTrash2></FiTrash2></button>
            
            <header>
            
            
            
            
            </header>
            <section>
                <ImgPet pet={pet}></ImgPet>
                
            
            </section>
            
            <strong>Recompensa:</strong>
            <p>{Intl.NumberFormat('pt-BR',{style:'currency',currency:'BRL'}).format(pet.value)}</p>
            
 
            <strong>Descrição:</strong>
            <p>{pet.description}</p>
           
            
           
           <form>

               
                

                      
        </form>
            
             <div className="link">
             <Link className="button"  onClick={()=>Position(pet.id,'position')}>Ver Localizações</Link>
             </div>
           
            

        </li>
        ))}
        
        </ul>
      
    </div>
       
    );
}

1 answer

3


In its code the useEffect need to know what to do, the code does not know what is the time of its stop or the moment that it can be executed.

Since the code should be executed only once when creating the component, you need to configure a array without any stipulated position, example:

useEffect(()=>{
    api.get('imagem',{
        headers:{
            authorization:pet.id,
        }
    }).then(response => setImagem(response.data))
},[]) // <--------------

this way will be executed the only time at the time of creation of the component.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.