skip to Main Content

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


  1. You can’t use useState in map you need to declare it in top (before return)

    const funName = () => {
        const [endDate, setEndDate] = useState();
        return (
            <>
                .........
                {data.map((eachData, index) => {
                    return (
                        <CustomComponent
                            key={index}
                            selected={endDate}
                            onChange={setEndDate}
                        />
                    );
                })}
            </>
        );
    };
    
    Login or Signup to reply.
  2. You cannot do it, use useState inside your Custom component, just forward "eachData" to that component and implement logic inside with useState.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search