I have a React app which makes a call in useEffect
to my API which returns a list of URLs to use as imy image srcs.
I am using react-loader-spinner
to show a loading spinner component while my images load.
I have a loading
variable in useState
to determine whether the images are loading.
I can not figure out how to stop showing the loading spinner and show my images once they have all loaded.
Here is my code:
Photos.jsx
import React, { useState, useEffect, Fragment } from 'react'
import Loader from 'react-loader-spinner';
import { getAllImages } from '../../services/media.service';
import Photo from '../common/Photo';
const Photos = () => {
const [photos, setPhotos] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
getAllImages()
.then(results => {
setPhotos(results.data)
console.log(results.data)
})
.catch(err =>{
console.log(err)
})
}, [])
const handleLoading = () => {
setLoading(false)
}
return (
<Fragment>
<div className="photos">
{ loading ?
<Fragment>
<Loader
height="100"
width="100"
/>
<div>Loading Joe's life...</div>
</Fragment>
:
photos.map((photo, index) => (
index !== photos.length - 1 ?
<Photo src={photo.src} key={photo.id} /> :
<Photo src={photo.src} key={photo.id} handleLoad={handleLoading}/>
))
}
</div>
</Fragment>
);
}
export default Photos;
Photo.jsx
import React from 'react'
import './Photo.css';
const Photo = (props) => {
return (
<div className="photo">
<img src={props.src} alt={props.alt} onLoad={props.handleLoad}/>
<div className="caption">
Photo caption
</div>
</div>
);
}
export default Photo;
I tried using onLoad
for my last item but it will never get called because loading
is never set back to false due to the spinner still being shown.
Some help on this would be greatly appreciated. Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…