'building dinamically array for react-simple-image-slider
React simple slider needs array of images at the star and some code inside html to initiate the slider
const images = [
{ url: "images/1.jpg" },
{ url: "images/2.jpg" },
{ url: "images/3.jpg" },
{ url: "images/4.jpg" },
{ url: "images/5.jpg" },
{ url: "images/6.jpg" },
{ url: "images/7.jpg" },
];
for images array I made
const [images, setImages] = useState([]);
maybe different way is better correct me pls. Then I have useEffect where I fetch the data
useEffect(() => {
const getData= async () => {
try {
const response = await fetch(`url`, {
fetch request....
const ImagesArray = imagesArrayfromFetch.map((image) => ({
url: `/img/${image}`,
}));
console.log(ImagesArray);
setImages(ImagesArray);
console.log(images);
When I console.log ImagesArray - it gives me correctly filled array object. console.log(images) gives me undefined. Here is an error probably Then inside html I build the slider object
const App = () => {
return (
<div>
<SimpleImageSlider
width={896}
height={504}
images={images}
showBullets={true}
showNavs={true}
/>
</div>
);
}
So because setImages do not put array inside images slider object creates without images. Is there a way to fix this?
Solution 1:[1]
It seems like you have a race condition.
Setting new state must happen after resolve.
Could be done in fetch().then( /* set state */ )
Cleaner way would be with await/async:
const fetchImages = async () => {
try {
const data = await fetch(...);
if (data) {
const ImagesArray = data.images.map((image) => ({
url: `/img/${image}`,
}));
console.log(ImagesArray);
setImages(ImagesArray);
}
} catch(error) {
console.error(error);
}
}
useEffect(() => fetchImages(), [])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | arcbjorn |
