Search code examples
react-hooksoffice-ui-fabricreact-tsx

onChange monitoring user input into TextField component from Office-UI-Fabric on every render and displaying incorrect output


I am trying to implement a UI where i take user input through the TextField component from Office-ui-fabric. I use onChange to monitor value. However, as i type in user input say the number '100' i can see the function rendered each time which i believe is a feature of onChange but after completing typing in my input i see only '10' in the console window.

I tried changing onChange to Blur as suggested in an old stackoverflow post but when i do that i don't see any console messages.

const [msg, setMsg] = React.useState("");
React.useEffect(()=>{
   vscode.postMessage(
     {
       command: 'setMsg',
       text: msg
     }
   );
},[msg])

return (
<div>
 <Stack>
   <Stack.Item grow>
   <Label style={{ color: 'white' }}>Enter number </Label>
   <TextField placeholder="Enter number of images" value={msg} onChange={event => { setMsg((event.target as HTMLInputElement).value); console.log(msg);test() }} /> 
   </Stack.Item>
   </Stack>
</div>
);

I expect if i enter the number '100' i should see '100' in the console log. Currently i see'10'. Is this the right way to implement this functionality? New to react and office -ui-fabric and any help is appreciated.


Solution

  • setState in React is async and takes some time to execute / update state.

    When you do this,

    onChange={event => { 
       setMsg((event.target as HTMLInputElement).value); 
       console.log(msg);
       test() 
    }}
    

    After setState you are trying to access the state which will in result gives you the previous state only.

    To see actual effect, remove this console.log from onChange and make use of useEffect hook. As you already have useEffect which will execute on msg change, you just need to add console.log(msg) line in it.

    React.useEffect(()=>{
            console.log(msg); // Now you will get updated value every time.
            vscode.postMessage(
                {
                    command: 'setMsg',
                    text: msg
                }
            );
    },[msg])