1

I'm using redux in a project and after returning an endpoint, I add a value in state, then I need to use this value that is in the state to send in another request.

The path that is the saved value is this:

form.state.code.code

And I did this:

const getValue = await getState().form.state.code.code ? getState().form.state.code.code : null;

I made this conditional to check if there is any value in the state, if it doesn't exist, it should return null

This code works, but I'm finding it very verbose, is there any way to improve it?

CodeG
  • 417
  • 2
  • 6
  • 15
  • you shouldn't need to await `getState`. You could use the nullsafe-operator([optional-chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)) to shorten the code. – Brian Thompson Jul 22 '21 at 18:52

1 Answers1

1

Using Object Destructuring

const {form: {state: {code = null} = null} = null} = await getState();
const getValue = code && code.code ? code.code : null;

or you don't need to use await getState, you can achieve using optional-chaning

const getEL = getState()
const getValue = getEL && getEL.form && getEL.form.state && getEL.form.state.code && getEL.form.state.code.code