So I am building a SPA using react and fetching some images from an API. I want to show a loader till i get a response. I have the code here but the loader does not seem to spin for some reason. I’m not sure why. I am using axios to fetch the API. I have the code for the components below.
photogallery.js
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable jsx-a11y/img-redundant-alt */
import React, { useState, useEffect } from "react";
import "./PhotoGallery.css";
import ImageModal from "./ImageModal";
import Loader from "./Loader";
import axios from "axios";
const PhotoGallery = () => {
const [isLoading, setIsLoading] = useState(false);
const [photos, setPhotos] = useState([]);
const [selectedPhoto, setSelectedPhoto] = useState(null);
const headers = {
Authorization: "my_key",
};
const fetchApi = async () => {
setIsLoading(true);
await axios
.get("https://api.pexels.com/v1/curated", { headers })
.then(({ data }) => {
const photoUrls = data.photos.map((photo) => photo.src.original);
setPhotos(photoUrls);
});
setIsLoading(false);
};
useEffect(() => {
fetchApi();
}, []);
const handlePhotoClick = (photo) => {
setSelectedPhoto(photo);
};
const handleCloseModal = () => {
setSelectedPhoto(null);
};
return (
<>
{isLoading ? (
<Loader />
) : (
<div className="photo-gallery">
{photos.map((photo, index) => (
<div
className="photo"
key={index}
onClick={() => handlePhotoClick(photo)}
>
<img src={photo} alt={`Photo ${index + 1}`} />
</div>
))}
{selectedPhoto && (
<ImageModal photo={selectedPhoto} onClose={handleCloseModal} />
)}
</div>
)}
</>
);
};
export default PhotoGallery;
Loader.js
import React from "react";
import "./Loader.css";
const Loader = () => {
return <div className="loader"></div>;
};
export default Loader;
Loader.css
.loader {
border: 4px solid rgba(0, 0, 0, 0.1);
width: 36px;
height: 36px;
border-radius: 50%;
border-left-color: #09f;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}