0

I have a component with the following handler:

<MyComponent onKeyDown={handler} />

The handler looks like this:

const handler = (e: KeyboardEvent) => {
  if (e.key === 'Backspace') {
    const slicedString = input.slice(0, -1);
    setInput(slicedString);
  }
};

And this is my useState hook:

const [input, setInput] = useState<string>('');

I want to slice the last character of the input when 'Backspace' is pressed onKeyDown event.

The slicedString gets updated when backspace is pressed but the input state stays the same. I know that the spread operator has to be used for objects and arrays but how can I update the state when a string is used?

Codehan25
  • 2,704
  • 10
  • 47
  • 94
  • I'm not seeing any issues with what you have posted. How are you reading/displaying the `input` state? – sma Jun 30 '22 at 14:02
  • As mentioned in my post - the slicedString gets updated, but setInput has no effect on my input. – Codehan25 Jun 30 '22 at 14:04
  • I understand that, but how do you know. Can you show the code where you're using `input`. – sma Jun 30 '22 at 14:05
  • Are you sure that your handler is being invoked? Perhaps you can add a `console.log` inside the definition and make sure that it is being called – jon doe Jun 30 '22 at 14:19
  • Yes it is invoked, that's the reason I know that the state is not updated. Added console.logs etc. – Codehan25 Jun 30 '22 at 14:21
  • This is really weird, everything looks fine and should work if your handler is being executed, You can try with `setInput(prev => prev.slice(0, -1))` but it would be even more confusing to me if that works, because `.slice` returns new string and is completely fine to do it in a way you did it. – Milos Pavlovic Jun 30 '22 at 14:27
  • Could you add an example in which this problem occurs? – TimmNL Jun 30 '22 at 15:05

0 Answers0