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...
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;

setStatefromuseStatedoes not work the same way as the class componentthis.setState. You will need to specify the complete state when usingsetStatei.e.setState({ index: index });should besetState({ ...state, index: index });stateis destructured in the lineconst { products, index } = state;sostate.products === products.