Best practice when trying to use async code inside an action

I'm working on a React Native with Expo project, right now i'm trying to delete an item from a list inside a local database. Problem is in the action where I send it. Here is my code.

  export const eliminatePlace = (placeId) => {
    console.log(`Inside the action with placeID ${placeId}`);
    return async dispatch => {
      console.log('returned');
      try {
        const dbResult = await deletePlace(placeId);
        console.log(dbResult);
        dispatch({
          type: DELETE_PLACE,
          id: placeId
        });
      } catch (err) {
        throw err;
        console.log(err);
      }
    };
  }

Somehow the console.log inside the return didn't fire up, my workaraound was this:

export const eliminatePlace =  async (placeId, dispatch) => {

  try {
    console.log(`Trying to eliminate place with ID ${placeId}`);
    const dbResult = await deletePlace(placeId);
    console.log(dbResult);
    dispatch({type: DELETE_PLACE, id: placeId});
  } catch (err) {
    throw err;
    console.log(err);
  }

};

Then it did work, but this is not the best practice, any ideas on why the correct way didn't work? Here is the link to my github repo where you can download the project: https://github.com/josmontes/rn-places In case someone needs to see another place of the code please ask, I didn't add anything else so it doesn't bloats the question and because the problem is inside this function.

Upvotes: 0

Views: 227

Answers (1)

giotskhada
giotskhada

Reputation: 2452

You shouldn't be calling async functions inside your action creators. You can read more about why here. Instead, you should use async actions. Even though you aren't making an API call, you can still represent your process as request-success-failure. Basically, dispatch a "request" action and as a side effect call your async function. Once it resolves, you dispatch either "success" or "failure" action, depending on the result. You can then put the results from the database in the payload of the "success" action. You can read more about that here.

I believe the the second example you gave works, because that's basically just the "success" action. It only dispatches a regular action once the async function resolves, while in the first example, the action function itself is async, which redux doesn't like.

Upvotes: 1

Related Questions