How to replace - mapDispatchToProps to useDispatch - REACT REDUX

Viewed 19

I am a beginner in Redux - I need to replace mapStateToProps and mapDispatchToProps to hooks.

I've replaced mapStateToProps to useSelector, but I'm having trouble replacing mapDispatchToProps to hook useDispatch.

Please give me some pointers and help to rewrite this code.

The code I attach below shows what I am currently working on.


       interface DepartmentsFilterOwnProps {
       id?: GenericId;
       name?: string;
       productCount?: number;
       checkboxIconSize?: CheckboxIconsSize;
       className?: string;
    }
    
    interface DepartmentsFilterStore {
       activeDepartmentsIds: GenericId[];
    }
    
    interface DepartmentsFilterActions {
       onDepartmentChange: (departmentId: GenericId) => void;
    }
    
    export type DepartmentsFilterProps = DepartmentsFilterOwnProps & DepartmentsFilterStore & DepartmentsFilterActions;
    
    export const DepartmentsFilter = ({
       id,
       name,
       productCount,
       checkboxIconSize,
       className,
       onDepartmentChange,
    }: DepartmentsFilterProps) => {
       const isChecked = activeDepartmentsIds.indexOf(id) > -1;
       const onChangeCheckbox = (departmentId: GenericId) => () => onDepartmentChange(departmentId);
       const isDisabled = !productCount;
    
       return (
          <P.FilterGroup className={className}>
             <P.Checkbox
                checked={isChecked}
                iconSize={checkboxIconSize}
                disabled={isDisabled}
                onChange={onChangeCheckbox(id)}
             >
                {name}
    
                <SelectFilterParts.FilterProductCount>{' '}({productCount})</SelectFilterParts.FilterProductCount>
             </P.Checkbox>
          </P.FilterGroup>
       );
    };
    
    const activeDepartmentsIds = useSelector(getDepartmentsActiveIdsSelector);
    
    /* istanbul ignore next */
    // const mapStateToProps: MapStateToProps<DepartmentsFilterStore, DepartmentsFilterOwnProps, ApplicationState> = (state) => ({
    //    activeDepartmentsIds: getDepartmentsActiveIdsSelector(state),
    // });
    
    /* istanbul ignore next */
    const mapDispatchToProps: MapDispatchToProps<DepartmentsFilterActions, {}> = (dispatch) => ({
       onDepartmentChange: (departmentId: GenericId) => {
          dispatch(toggleDepartment(departmentId));
       },
    });
    
    export default connect(null, mapDispatchToProps)(DepartmentsFilter);
1 Answers

The correct way to use useDispatch hook is something like this:

import { useDispatch } from 'react-redux'

export const DepartmentsFilter() {
  //assign it to a new variable
  const dispatch = useDispatch()

  //use it somewhere, for example:
  useEffect(() => {
    dispatch({ type: 'YOUR_SAGA' })
})

than delete the mapDispatchToProps and the connect

Related