0

I have an input field that needs an onChange event to be bound on mounting the component. The onChange event needs to update the state. However, the state never gets updated because the onChange event always has the initial state. What is the best way to make this work?

Here is my code:

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

    useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])
}
Eric P Pereira
  • 450
  • 1
  • 7
  • 18
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Drew Reese Mar 06 '20 at 04:25
  • 1
    Also, you usually attach event handlers to the element/component yielding the event. – Drew Reese Mar 06 '20 at 04:30
  • 1
    Why do you want to bind an event change on mount? Wouldn't be adding a change handler to InputField suffice? – Vishnu Mar 06 '20 at 04:33
  • @Vishnu i have JSON file containing the structure of the input elements required on my page. This is to allow flexibility of fields. I then read the JSON file, use it inside my React component and then need to attach an onChange function to handle changes to the inputs. – Eric P Pereira Mar 06 '20 at 10:11
  • @EricPPereira be that as it may, this isn't quite how handlers are attached to components. You have a couple issues, first is connecting your `onChange` handler to the input component and the second is correctly accessing updated state/not enclosing stale state. Please share a [Minimal, Complete, and Reproducible](https://stackoverflow.com/help/mcve) example and try to limit it to a single specific problem. – Drew Reese Mar 06 '20 at 19:47
  • @EricPPereira Is this what you are looking for? [link](https://stackoverflow.com/questions/56168321/generate-react-form-fields-from-json) – Vishnu Mar 07 '20 at 04:50
  • @Vishnu i'll have a look. – Eric P Pereira Mar 09 '20 at 10:50

1 Answers1

0

You can tweek your useEffect to get the updated state. State setting is async in nature. -

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

  useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])

    useEffect(() => {
        console.log(count) //updated value//
    }, [count]) // adding count to dependency array will cause this  useEffect to run on every count change //
}
Atin Singh
  • 3,624
  • 2
  • 18
  • 25