locked
hook issue RRS feed

  • Question

  • User1034446946 posted

    Hi

    I have built a form validator, which is inside a .forEach loop and i ge the error saying it cannot be in a loop

    i also want to use useSelector inside a.foreach loop

    if i put

    const selector = useSelector()

    at the top and

    van stateObj = selector i get

     React Hook "useSelector" 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

    which works for dispatch

    how do i get around this, (also how do i find this sort of stuff out by looking at the code)

    Saturday, September 7, 2019 2:11 AM

Answers

  • User-474980206 posted
    Hooks are for lifecycle events. State hooks allow dispatching state changes which will rerender the component tree. Not sure why a form validation would need a useSelector in a for loop. There is just one validate event, which would update state via dispatches for all fields in the form.

    Typical validation is done by state having a tree of validation states. The validation event updates the state, and the validation display components display the state. Here is a pretty typical example

    https://hackernoon.com/react-form-validation-using-react-hooks-5859c32280ca




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 7, 2019 5:07 PM

All replies

  • User1034446946 posted

    i sort of get the issue, but surely useSelector and reducers always start at the base state, so i don't get where there'd be conflict, alli want to do is check if an error is already in state and add or delete it if it is.

    Saturday, September 7, 2019 1:40 PM
  • User-474980206 posted
    Hooks are for lifecycle events. State hooks allow dispatching state changes which will rerender the component tree. Not sure why a form validation would need a useSelector in a for loop. There is just one validate event, which would update state via dispatches for all fields in the form.

    Typical validation is done by state having a tree of validation states. The validation event updates the state, and the validation display components display the state. Here is a pretty typical example

    https://hackernoon.com/react-form-validation-using-react-hooks-5859c32280ca




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 7, 2019 5:07 PM
  • User1034446946 posted

    will look through the example in a moment, basically,

    my thought was if validate failed i would check to see if the error was there, if i wasn't add it, and the opposite for if validation had passed.

    i guess this should be another question but should i be using useEffect to stop rerendering by default to only render is state in that component has changed?

    Saturday, September 7, 2019 8:38 PM