Reputation: 17
I'm currently working on a website using Strapi as a CMS and Next.js(React) in Frontend. The site also has an image slider which obviousely contains an image, a headline and a description. These three things I now want to get from my Strapi Collection Type called Banner (Banners). I've tried so many times and read through every forum I could find, but it somehow still doesn't work. There's no error, but the data I want to display doesn't show up on the website. The following code is the one from \frontend\components\image-slider.js:
import React from "react";
const Slider = ({}) => {
const [banners, setBanners] = React.useState(null);
const getBanners = async() => {
const res = await fetch("http://localhost:1337/banners");
const json = await res.json();
setBanners(json);
}
if(!banners){
getBanners();
}
if (typeof window !== 'undefined') {
// Code for making slider work
}
return (
<div className="img-slider">
<div className="slide active">
<div className="info">
<div>
{banners ? banners.map((banner) => (
<div key={banner.id}>
<h2>{banner.title}</h2>
</div>
)) : (
<div>Loading...</div>
)}
</div>
<p>
{banners ? banners.map((banner) => (
<div key={banner.id}>
<h2>{banner.description}</h2>
</div>
)) : (
<div>Loading...</div>
)}
</p>
{/* <Image></Image>This I haven't tried yet. */}
</div>
</div>
<div className="slide">
{/* Same code as div before */}
</div>
{/* further slides */}
<div className="navigation">
<div className="btn-navig active"></div>
<div className="btn-navig"></div>
<div className="btn-navig"></div>
</div>
</div>
)
}
export default Slider;
The type of how I currently try to get the data is from this StackOverflow answer. I hope someone is able to help me! Thanks a lot!
Upvotes: 0
Views: 2100
Reputation: 86
You have to put your API request (getBanners) in useEffect hook with [] as a dependencies (run only once - on load) like so:
React.useEffect(() => {
const getBanners = async() => {
const res = await fetch("http://localhost:1337/banners");
const json = await res.json();
setBanners(json);
}
getBanners();
}, [])
Upvotes: 1