lundi 30 août 2021

Show image only if the image is loaded from the database

I have a problem. I am searching in a database to see if a picture exists. If the image is not present, a "No Image" image is set. If an image is available, the current image from the database is displayed.

What I would like to do now is to display a loading spinner, which should only be displayed if an image is available in the database and the image from the database is still loading.

I now have the following problem: when I load an image from the database, everything fits. However, as soon as I don't have an image from the database, "No Image" is displayed and the loading spinner is also displayed. How can I now say that only the loading spinner should be displayed if dataPic is not zero and the image has not yet loaded?

import React, { useEffect, useState, useRef } from 'react'
import axios from 'axios'
import { Spinner } from 'react-spinners-css';

import nophoto from '../../../data/images/nophoto.png'

const id = (window.location.pathname).split("-")[1];

function Team() {

    const [imgLoaded, setImgLoaded] = useState(false);  

    const [dataPic, setDataPic] = useState(null);
    const getPhoto = () => {
        axios
            .get(`${process.env.REACT_APP_API_URL}/photo-${id}`,

        )
            .then((res) => {
                if (res.status === 200) {
                    var parts = res.data.split(",");
                    var result = parts[parts.length - 1];
                    setDataPic(result);
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    useEffect(() => {
        getPhoto();
    }, []);

    return (
        <div>
            {/*here ist the problem*/}
            {imgLoaded && dataPic === null ? null :
                <div>
                    <Spinner color="#5869FF" style= />
                    <p>Is loading...</p>
                </div>
            }
            {
                dataPic === null ?
                    <img src={nophoto} alt="hi"/>
                    :
                    <img src={`data:image/png;base64,${dataPic}`} alt="hi" onLoad={() => setImgLoaded(true)} />

            }


    )
}

export default Team

Aucun commentaire:

Enregistrer un commentaire