0

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?

1 Answer 1

2

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(), [])
Sign up to request clarification or add additional context in comments.

2 Comments

doing just like that but get undefined array
I've updated my question. my fetch was the same as yours, I just did not write the detailed code. But problem is somewhere else cause console.log(images) after setImages gives empty array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.