Getting below error while trying to update a preloaded value onchange using useState inside map
React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
I’m trying to display a value from data array on a custom date field and on change update it to new selected date. When I’m trying to use a useState hook inside a map, I’m getting the below error. I’m a beginner in react and trying to figure out how to fix. Thanks in advance.
const funName = () => {
return (
<>
.........
{data.map((eachData, index) => {
const [endDate, setEndDate] = useState("new Date(eachData.eDate)");
return (
<CustomComponent
key={index}
selected={endDate}
onChange={(date) => setEndDate(date)}
/>
);
})}
</>
)
}
2
Answers
You can’t use
useState
inmap
you need to declare it in top (before return)You cannot do it, use useState inside your Custom component, just forward "eachData" to that component and implement logic inside with useState.