Search code examples
reactjsreact-hooksreact-functional-componentuse-reducer

from legacy state to useReducer nested elements React


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?


Solution

  • 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