相关文章推荐
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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)}

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}
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

 
推荐文章