0

Este es el error que me tira el codigo, no se porque no encuentra, cuando luego de borrar esa "url" que no encuentra, se carga el State y puedo mostrarlo perfectamente

Esta es mi peticion al BACK con un useEffect()

const HomeHeroe = ({handle}) => {


const id = useParams();
const routerHistory = useHistory();
const resultSession = localStorage.getItem('token');
const [heroe,setHeroe] = useState([]);

const [isFetching,setIsFetching] = useState(false);

 useEffect(()=>{
     setIsFetching(true);
    const HereoById = async (id)=>{
        await api.post('/index', id).then((res)=>{
            console.log(res.data);
            
           return  setHeroe({...res.data});
         
        }).catch((err)=>{
            console.log(err);
        });
    };
    HereoById(id);
    setIsFetching(false);
 },[]);

Aqui tenemos el return, que luego de actualizar la pagina, me devuelve los datos sin nigun tipo de problema, hasta que llega un punto que si cargo algun dato mal o si pongo heroe.image.url me devuelve ese error de que no esta definida la propiedad. **

return (<>
    {!resultSession ? (alert("Sin autorizacion para el sitio, Ingrese"), routerHistory.push('/login')) :
        <>
        <div>
            <div className="m-0 row  justify-content-center">
                <div className="col-auto">
                    <button onClick={footerOut} className='btn btn-block bg-success mb-2 mt-2 ml-2'>Quitar Footer</button>
                </div>
                <div className="col-auto">
                    <button onClick={footerOn} className='btn btn-block  bg-success mb-2 mt-2'>Ver Footer</button>
                </div>
               
            </div>
            <div className="m-0 row  justify-content-center">
              
            </div>
        </div>
    
    <Container >
        <Row>
   
            <Col className='text-center mb-2'>
            <Card className='cardHero' border="danger">
            
         
                <Card.Body>
                <a><img src={heroe.image.url}/></a>
                {isFetching && <Loading />}
                 <Card.Title>{heroe?.name}</Card.Title>
                 <a> <img /> </a> 
                 <Card.Header>{Object.keys(heroe.connections)}</Card.Header>
                 <Card.Header>{Object.values(heroe.connections)} </Card.Header>
                 <Card.Text>
                 </Card.Text>
                {/* <Button onClick={()=>{routerHistory.push('/home')}}>Boton,VerQueHacer</Button> */}
                </Card.Body>
             </Card>
            </Col>
        </Row>

        
         </Container>
         </>
   

}
</>);

}

export default HomeHeroe;

LUEGO AL BORRAR ESOS DATOS SUPUESTAMENTE ERRONEOS, ME DEVUELVE EL STATE CARGADO Y PUEDO MOSTRAR LOS DATOS COMO QUIERO. NO LOGRO SOLUCIONARLO, ALGUNA IDEA?? GRACIAS COMUNIDAD COMO SIEMPRE!!! LA IMAGEN DEL JSON PUESTO EN PANTALLA CON LA DEVOLUCION DEL STATE POR CONSOLA

1 respuesta 1

0

Estás seteando mal el valor de tu state. Lo inicializas como un array vacío, pero en el setHeroes de tu useEffect conviertes la respuesta de tu request a un objeto.

setHeroe(res.data)

Esto debería funcionar. Y lo otro, es que no necesitas retornar el state ;)

Nos comentas cualquier cosa.

1
  • Gracias mi amigo. Claramente me sirvio, un error tan tonto me llevo tantos dolores de cabeza!!! gracias!! el 7 ene. 2022 a las 21:43

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.