facebookarchive / redux-react-hook

React Hook for accessing state and dispatch from a Redux store
MIT License
2.16k stars 103 forks source link

How to chain actions? #64

Closed Kelbie closed 5 years ago

Kelbie commented 5 years ago
export const editSection = (section) => ({
  type: ACTION_TYPES.EDIT_SECTION,
  payload: section
});

export const openModal = () => ({
  type: ACTION_TYPES.OPEN_MODAL
});

export const closeModal = () => ({
   type: ACTION_TYPES.CLOSE_MODAL  
});

How can I make it so that when I call editSection it dispatches openModal? I was just going to do dispatch(openModal) but that requires useDispatch which can only be declared inside a react function as far as I'm aware.

Seru88 commented 5 years ago

Why not handle it as a side effect?

const MyComponet = () => {
  const mapState = React.useCallback(
    state => ({
      sectionToEdit: state.section,
    })
  );

  const { sectionToEdit } = useMappedState(mapState);

  const dispatch = useDispatch();

  const dispatchEditSection = React.useCallback(
    section => dispatch(editSection(section)),  [dispatch]
  );

  const dispatchOpenModel = React.useCallback((
    () => dispatch(openModel()),  [dispatch]
  );

  React.useEffect(() => {
      dispatchOpenModel();
    }, [sectionToEdit]) 
  }

  return (
  <button onClick={() => dispatchEditSection("some section")}>
    Edit Some Section
  </button>
  );
}

You can also use the dispatch function straight from your store object. https://redux.js.org/api/store#dispatchaction

ianobermiller commented 5 years ago

I wouldn't recommend making this an effect. Ideally, a single user action corresponds to a single Redux action. So, your reducer should handle EDIT_SECTION and also open the modal at the same time.

Closing as this isn't really a redux-react-hook specific question, and we can discuss more if you need.