How to replace - mapDispatchToProps to useDispatch - REACT REDUX

730 Views Asked by At

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.

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);
   
    const mapDispatchToProps: MapDispatchToProps<DepartmentsFilterActions, {}> = (dispatch) => ({
       onDepartmentChange: (departmentId: GenericId) => {
          dispatch(toggleDepartment(departmentId));
       },
    });
    
    export default connect(null, mapDispatchToProps)(DepartmentsFilter);
1

There are 1 best solutions below

0
On

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