API data are not rendering in img tag using useEffect()

159 Views Asked by At

I'm trying to fetch the data from API and passing the response to img src and it is showing the state value as 'undefined'. In the below code, I tried to set the "bannerImage" state in useEffect and it is throwing 'undefined'.I tried with normal function as well, its giving 'bannerImage' as an empty value.

Note: The value of "res" in then statement is showing the url, but when setting to state only its not working.

    function Carousel(props) {
      let CarouselSettings = CarouselSetting.homePageBannerCarousel;
      const [bannerImage, setBannerImage] = useState();
    
      const serviceEndpoint = config.serviceHost + "/mycompany";
    
      useEffect(() => {
        props.carouselData.map((data) => {
          //setBannerDetail(data);
          return axios
            .get(
              serviceEndpoint +
                config.apiUrl.getAllAppImage +
                "/?id=" +
                data.pbDtlId +
                "&&vendorId=1" +
                "&&filecatcode=" +
                getFilecatcode.banner
            )
            .then(res => setBannerImage(res );
        });
      });

      console.log(bannerImage, "===banner");
      return (
        // <div className="pt-40">
        <div className="slider-wrapper relative top-130 py-8 px-10 bg-gray-100">
          <Slider {...CarouselSettings}>
            {props.carouselData.map((data) => {
              return (
                <div>
                  <div>
                    <h1 className="text-3xl font-semibold">{data.bannerTitle}</h1>
                    <h4 className="text-xl py-5">
                      {data.bannerDesc1} {data.bannerDesc2}
                    </h4>
                    <h4 className="text-xl pb-5">{data.bannerDesc3}</h4>
                   <img src={bannerImage}/>
                  </div>
                </div>
              );
            })}
          </Slider>
        </div>
      );
    }
    
    export default Carousel;
2

There are 2 best solutions below

3
On BEST ANSWER

Set the image for each item, instead of using the same variable for all the items in the carousel data. In your useEffect loop over the carousel data and add another prop for src.

function Carousel({ carouselData }) {
  let CarouselSettings = CarouselSetting.homePageBannerCarousel;
  const [carousel, setCarousel] = useState([]);

  const serviceEndpoint = config.serviceHost + "/mycompany";

  useEffect(() => {

    const getBannerImages = async () => {

      const data = await Promise.all(carouselData.map(async (item) => {
      // get the image url and set it to the item and access it in your render with data.src
        const src = await axios.get(
          serviceEndpoint +
            config.apiUrl.getAllAppImage +
            "/?id=" +
            item.pbDtlId +
            "&&vendorId=1" +
            "&&filecatcode=" +
            getFilecatcode.banner)

        return {
          ...item,
          src
        }

      }));

      setCarousel(data);

    }

    getBannerImages()
    .catch(e => console.log(e));

  }, [carouselData]);

  return (
    // <div className="pt-40">
    <div className="slider-wrapper relative top-130 py-8 px-10 bg-gray-100">
      <Slider {...CarouselSettings}>
        {carousel.map((data) => {
          return (
            <div>
              <div>
                <h1 className="text-3xl font-semibold">{data.bannerTitle}</h1>
                <h4 className="text-xl py-5">
                  {data.bannerDesc1} {data.bannerDesc2}
                </h4>
                <h4 className="text-xl pb-5">{data.bannerDesc3}</h4>
              <img src={data.src}/>
              </div>
            </div>
          );
        })}
      </Slider>
    </div>
  );
}

export default Carousel;
0
On

Try the below approach,

useEffect(() => {
    props.carouselData.map((data) => {
      //setBannerDetail(data);
      return axios
        .get(
          serviceEndpoint +
            config.apiUrl.getAllAppImage +
            "/?id=" +
            data.pbDtlId +
            "&&vendorId=1" +
            "&&filecatcode=" +
            getFilecatcode.banner
        )
        .then(res => {
            setBannerImage(res);
      });
    });
  }, []);