0

i have this legacy code where we have height as an object with heightUnits nested inside it,

before we were changing the height like so

 this.setState(prevState => ({
    height: {
    ...prevheight,
    [heightUnit]: heightValue
    }
   }));

and i turned the above code into a dispatch like so

const onChangeHeight = useCallback((heightValue, heightUnit) => {
    dispatch({ type: 'height-change', [heightUnit]: heightValue });
    clearErrors();
  }, [clearErrors]);
    case 'height-change': return { ...state, height: { ...state.height, heightUnit: action.heightUnit }};

but the value is being returned as undefined did I translate the code from class components to functional components correctly?

Asker
  • 97
  • 1
  • 11
  • It doesn't look like `action.heightUnit` is defined, so when you try to set state with it, there's nothing there. This: `[heightUnit]` uses this the stored value of `heightUnit` as the key in the `action` object. `action` _has no_ key named `heightUnit`. – Matt Morgan May 16 '21 at 12:03
  • thank you @MattMorgan you did open my eyes to check that and you are right, apparently, the legacy code meant that [heightUnit] is treated as a key rather than data so it worked – Asker May 16 '21 at 16:40

1 Answers1

0
const onChangeHeight = useCallback((heightValue, heightUnit) => {
    dispatch({ type: 'height-change', heightUnit, heightValue });
    clearErrors();
  }, [clearErrors]);
case 'height-change': return { ...state, height: { ...state.height, [action.heightUnit]: action.heightValue }};

the brackets indicate that heightUnit is a key inside the height object getting the valye from the onChangeHeight Function

Asker
  • 97
  • 1
  • 11