1

I am binding a method to a button inside the useEffect hook, and the method internally is making use of state. But I am not getting the updated state inside the method to be binded instead getting state value as initialSate

If I pull the code outside the useEffect hook, everything works fine but not sure if this is the correct way.

function Test() {
    const initialState = { name: ''}
    const reducer = () => {...}
    const [state, dispatch] = useReducer(reducer, initialState);
    const save = (): void => {
        ...
         const { name } = state;
         // here i am getting state value as the initialState and not the
         // updated state value
        ...
    }
    useEffect(() => {
        ...
        bindActionToButton(button, save);
        ...
    }, []);
}

The save method is bound to the click event of the button.On clicking the button, the value of state inside the state should be the updated state value but I am getting value as initalState value. If I call pull the code outside the useEffect everything works fine.

Rohit Goyal
  • 212
  • 1
  • 2
  • 8
  • Why do you need the bindActionToButton? – Ori Drori May 13 '19 at 18:21
  • I have written a presentation header component having a list of buttons which will change based on the current Route, so need to bind action to them once the component mounts – Rohit Goyal May 13 '19 at 18:30
  • You should look again on how "binding" event handlers work. It's declarative, and you pass the functions as props. – Ori Drori May 13 '19 at 18:32
  • actually I need to bind different methods to the button in header based on the current route, and the current rendered component is having the definition of the method which needs to be bounded. In the current scenario I am trying to bind the save method to the click event of the button. – Rohit Goyal May 13 '19 at 18:38
  • You don't need to bind in React, unless you are targeting a standard DOM node outside of react. – Ori Drori May 13 '19 at 18:40
  • See https://stackoverflow.com/a/53846698/3731501 . Once it's useReducer, it's impossible to use state updater. – Estus Flask May 13 '19 at 19:04

0 Answers0