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;
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.