downshift icon indicating copy to clipboard operation
downshift copied to clipboard

How do I access key value in stateReducer

Open shallow-alchemy opened this issue 7 years ago • 5 comments

I need to make special logic for pressing the backspace key inside of the state reducer and would like a clean way to access that inside of the stateReducer property. How can I do this?

shallow-alchemy avatar Oct 08 '19 18:10 shallow-alchemy

Not sure it's a good place to apply your logic, stateReducer will only give you events such as Downshift.stateChangeTypes.changeInput and you need to figure it out if backspace was pressed (comparing previous and next inputValue).

You can add a custom onKeyDown to getInputProps and do your backspace logic there if possible, since there you will have access to the event and can get the key from it.

Otherwise the first option if you really need previous and next state available to you. What do you actually need?

silviuaavram avatar Oct 09 '19 07:10 silviuaavram

I want to return changes if a key is pressed when the state (inputValue) is less than 6 characters long. If it's longer than that, I want to return the state. But if it's 6 characters long and the backspace is pressed, I want to return the changes so that it reflects the deletion of the last character.

I thought of one way to do this (typescript, thus the bangs): const pressedBackspace = state.inputValue!.length - changes.inputValue!.length === 1

shallow-alchemy avatar Oct 09 '19 12:10 shallow-alchemy

don't we expose typings for DownshiftState ?

Edit:

  stateReducer?: (
    state: DownshiftState<Item>,
    changes: StateChangeOptions<Item>,
  ) => Partial<StateChangeOptions<Item>>

Edit 2: Why not just compare changes.inputValue.length to 6 and return inputValue as changes.inputValue only if it's less or equal than that? Otherwise just return state.inputValue as inputValue.

silviuaavram avatar Oct 09 '19 12:10 silviuaavram

I don't have those typings. I get a typescript error saying those are undefined. Am I missing an import somewhere? Downshift v3.3.4

Comparison as you said works too.

shallow-alchemy avatar Oct 09 '19 13:10 shallow-alchemy

Import them like this

import Downshift, {
  DownshiftState,
  StateChangeOptions,
  GetMenuPropsOptions,
  GetPropsCommonOptions,
  GetInputPropsOptions,
  GetToggleButtonPropsOptions,
  GetItemPropsOptions,
  ... anything else you need
} from 'downshift'

silviuaavram avatar Oct 09 '19 15:10 silviuaavram