Pep
Pep

Reputation: 677

Uncaught TypeError: Cannot read property 'map' of undefined - React js

I'm trying to set the new state with setState({index: index }) by passing the index but I got the following error

"Uncaught TypeError: Cannot read property 'map' of undefined" I'm using react hooks and also I'm using an arrow function, I do not really understand what's going on...

enter image description here

Any suggestion on how to fix this issue?

import { useState } from "react";
import "./App.css";

const App = () => {
  const [state, setState] = useState({
    products: [
      {
        _id: "1",
        title: "Shoes",
        src: [
          "https://www.upsieutoc.com/images/2020/01/07/img2.png",
          "https://www.upsieutoc.com/images/2020/01/07/img2.png",
        ],
     
      },
    ],
    index: 0,
  });

  const { products, index } = state;
  console.log("index", index);

  const handleTab = (index) => {
    console.log("index", index);
    setState({ index: index });
  };

  return (
    <div className="App">
      {products.map((item) => (
       <div className="details" key={item._id}>
          <div >
            <img src={item.src[index]} alt="" />
          </div>

          <div>
        
            <div className="thumb">
              {item.src.map((img, indx) => (
                <img
                  src={img}
                  alt="img"
                  key={indx}
                  onClick={() => handleTab(indx)}
                />
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default App;

Upvotes: 1

Views: 352

Answers (2)

Ari Firmanto
Ari Firmanto

Reputation: 344

The reason is your products state is replace by index state in handleTap function. useState will replace the current state with new state if you don't include current state.

It will be better if you separate product state and index state. For example:

const [products, setProducts] = useState([
  {
    _id: "1",
    title: "Shoes",
    src: [
      "https://www.upsieutoc.com/images/2020/01/07/img2.png",
      "https://www.upsieutoc.com/images/2020/01/07/img2.png",
    ],
 
  },
])
const [index, setIndex]= useState(0);

then in your handleTab function just call setIndex to update the Index

Upvotes: 1

Nghi Nguyen
Nghi Nguyen

Reputation: 950

When you setState({ index: index }) it remove the products property inside your state. Then do it instead

setState({ products, index: index })

Upvotes: 2

Related Questions