Can ActionCreators and Actions be mixed with Redux?

43 Views Asked by At

My experience is mostly with React Hooks & Context, where Actions & Reducers are defined. The Actions are then imported into a React component and called via a Dispatch function.

On a new project, I must use React Hooks & Redux. Here I'm using Action Creators & Reducers. Here's an example of an Action Creator I've created:

export const fetchCompanies: ActionCreatorThunk = () => {
  return function (dispatch, getState) {
    dispatch({ type: FETCH_COMPANIES_REQUEST });

    requests
      .get(
        `${requests.API_ROOT()}companies`,
        null,
        true
      )
      .then((response) => {
        dispatch({ type: FETCH_COMPANIES_SUCCESS, payload: response.data.companies });
      })
      .catch((error) => {
        console.error(error);
        dispatch({ type: FETCH_COMPANIES_FAILURE, payload: error.response });
      });
  };
};

This works great.

Here's my situation: I need to have an action to create an "empty" company, so there's no need to create an Action Creator. Thus I created an Action like this:

export const INIT_EMPTY_COMPANY: ActionType = 'INIT_EMPTY_COMPANY';
export type InitEmptyCompanyAction = { type: typeof INIT_EMPTY_COMPANY };

With the Action Creator, I was calling it from inside a useEffect like this:

dispatchRedux(fetchCompanies());

With the Action, I thought I could call it in a similar style to the way I always called actions with Context, like this:

dispatchRedux({ type: InitEmptyServiceFormAction });

Unfortunately I'm getting this Flow error: "Cannot reference type InitEmptyCompanyAction [1] from a value position."

What am I doing wrong and how I can fix this?

1

There are 1 best solutions below

0
On

I figured it out but feel dumb that I didn't see it before. I somehow got it in my mind that INIT_EMPTY_COMPANY was a type. It does indeed have a type, namely ActionType but it is not a type itself. My failure was trying to import it as a type.

Need more sleep, I guess!