Skip to content

Instantly share code, notes, and snippets.

@ErAz7
Created November 2, 2022 15:15
Show Gist options
  • Select an option

  • Save ErAz7/1bffea05743440d6d7559afc9ed12ddc to your computer and use it in GitHub Desktop.

Select an option

Save ErAz7/1bffea05743440d6d7559afc9ed12ddc to your computer and use it in GitHub Desktop.
mapDispatchToProps with react hooks

to avoid calling redux dispatch() coming from useDispatch directly in your components, you can simply create a wrapper over useDispatch that works similar to mapDispatchToProps in connect:

import { useDispatch, useSelector } from "react-redux";

export default function useMapDispatch(map) {
    const mapped = {};

    const dispatch = useDispatch();
    const state = useSelector((state) => state);

    for (const key in map) {
        mapped[key] = (...args) => map[key](...args)(dispatch, state);
    }
    
    return mapped;
}

then in your component:

// ...
const { fetchUser } = useMapDispatch({ fetchUser: fetchUserStore });

async function handleClick() {
  await fetchUser('USER_ID');
  console.log('user fetched');
}
// ...

and finally in the store function:

const fetchUserAsyncThunk = createAsyncThunk('fetchUser', async (userId) => {
  const response = await fetchUserApi(userId);
  return response.data
})

export function fetchUserStore(userId) {
  return (dispatch, state) => {
      return dispatch(fetchUserAsyncThunk(userId))
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment