javascript – Getting first element from a child prop in react JS

My Images.js is as follows:

`

import { useState, useEffect } from "react"; 
import axios from "axios"; 
import styled from "styled-components";

import ImageSlider_1 from "./ImageSlider_1";

const url = "https://hp-api.onrender.com/api/characters";

function Images() {   
  const [isLoading, setIsLoading] = useState(true);   
  const [isError, setIsError] = useState(false);   
  const [characters, setCharacters] = useState([]);

  useEffect(() => {
    const fetchCharacters = async () => {
      try {
        const response = await axios(url);
        const data = await response.data;

        data.map((character) => {
          if (character.image.localeCompare("")) {
            setCharacters((characters) => [...characters, character]);
          }
        });
      } catch (error) {
        setIsError(true);
        console.log(error);
      }
      setIsLoading(false);
    };
    fetchCharacters();   }, []);

  return (
    <Wrapper>
      <ImageSlider_1 characters={characters} />
      {/* <Carousel_Swiper characters={characters} /> */}
    </Wrapper>   ); }

const Wrapper = styled.section``;

export default Images;

`

My ImageSldier_1.js is as follows:

import { useState } from "react";
import styled from "styled-components";

function ImageSlider_1({ characters }) {
  console.log(characters[0].image);

  // const [sliderData, setSliderData] = useState(characters[0].image);
    
  return (
    <Wrapper>
      {characters.map((character) => {
        return (
          <img src={character.image} alt={character.name} key={character.id} />
        );
      })}
    </Wrapper>
  );
}

const Wrapper = styled.section``;

export default ImageSlider_1;

I am not sure why characters[0].image gives me error as this:

Uncaught TypeError: Cannot read properties of undefined (reading ‘image’)

However, when I do:

console.log(characters);

instead, it shows me there are 25 items.

I can do:

characters.map((character) => console.log(character.image));

to display each of the image link, but then I need to set first image in the state variable:

const [sliderData, setSliderData] = useState(characters[0].image); 

I am not sure what I am doing wrong. Please somebody help me out.

Thanks

Read more here: Source link