1
votes

I'm getting this error every time I try to dispatch my action:

Error: Actions must be plain objects. Use custom middleware for async actions.

I've installed redux-thunk and without async actions, it's working.

Store config:

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';

import reducers from '../reducers/index';

const logger = createLogger();

export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)));

UI:

...
import { connect } from 'react-redux';
import { getCities } from '../../actions/cities';
...
componentDidMount = async () => {
    try {
      const cities = await this.props.getCities();
      console.log(cities);
    } catch (error) {
      console.log(`errorhome: ${error}`);
    }
    SplashScreen.hide();
  }
...

const mapDispatchToProps = dispatch => ({
  changeNetworkStatus: () => dispatch(changeNetworkStatus),
  getCities: () => dispatch(getCities),
});

export default connect(mapStateToProps, mapDispatchToProps)(Home);

Action:

import database from '../config/utils';

export const GET_CITIES_START = 'GET_CITIES_START';
export const GET_CITIES_FINISHED = 'GET_CITIES_FINISHED';
export const GET_CITIES_ERROR = 'GET_CITIES_ERROR';

const getCititesStart = () => ({ type: GET_CITIES_START });
const getCititesFinished = cities => ({ type: GET_CITIES_FINISHED, cities });
const getCititesError = error => ({ type: GET_CITIES_ERROR, error });

export const getCitites = () => async (dispatch) => {
  dispatch(getCititesStart());
  try {
    const cities = [];
    const snap = await database.ref('cities').once('value');
    console.log('snap: ', snap);
    snap.forEach((element) => {
      const city = {
        city: element.key,
        coordinate: element.val().coordinate,
      };
      cities.push(city);
    });
    dispatch(getCititesFinished(cities));
  } catch (error) {
    dispatch(getCititesError(error));
  }
};

EDIT: If I add logger to middlewares too, the error message is this:

TypeError: Cannot read property 'type' of undefined

Thanks for your help!

1
For others that end up here. Make sure that you don't have extra asyncs lying around on your functions. This caused me to get the error message in the title. If there's no await in the function there should be no async in its header.worldsayshi

1 Answers

1
votes

Actions are functions that return a object with action's data, that data is a object with a type property.

You're dispatching action like this:

dispatch(getCities)

You should dispatch action like this:

dispatch(getCities())