Home > Back-end >  can´t access specific element of my array React
can´t access specific element of my array React

Time:09-20

I've a problem with my react app.The navbar worked correctly before the ItemDetailContainer, and i want to show in the DOM an specific product. When adding the ItemDetailContainer to app.js, the page doesn't show anything (including the navbar) . Here's my code:

ItemDetailContainer.jsx:

const {products} = require('../utils/data');

const ItemDetailContainer = () => {
    const [arrayList, SetArrayList] = useState({});

    useEffect(() => {
        customFetch(2000, products[0])
            .then(result => SetArrayList(result))
            .catch(err => console.log(err))
    }, [])

    return (
        <div>
            <ItemDetail products={arrayList}/>
        </div>
    );
}

here's my array in data.js that i want to access:

const products = [
    {
        id: 1,
        image: "https://baltimore.com.ar/img/articulos/4188.png",
        title: "Vino Abras Malbec 750cc",
        price: 2.500,
        stock: 8,
        initial: 1
    }

ItemDetail.jsx:

const ItemDetail = ({product}) => {
    return(
        <>
        {product.image}
        {product.title}
        </>
    )
}

CustomFetch.js:

let is_ok = true

let customFetch = (time, array) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (is_ok) {
                resolve(array)
            } else {
                reject("error")
            }
        }, time)
    })
}

and my app.js:

function App() {
  return (
    <div>
      <Navbar/>
      <ItemDetailContainer/>
    </div>
  );
}

I've done all the imports and exports, but I dont' know what's the problem.

CodePudding user response:

Since you are passing a product prop in <ItemDetail product={arrayList}/> within ItemDetailContainer make sure you destructure your props correctly in ItemDetail component,like so :

const ItemDetail = ({product}) => {
  return(
      <>
      {product.image}
      {product.title}
      </>
  )
}

Which is basically like this :

const ItemDetail = (props) => {
  return (
    <>
      {props.product.image}
      {props.product.title}
    </>
  );
};

check it out in code sandbox

  • Related