AnApprentice
AnApprentice

Reputation: 110960

How to use .dispatch in react redux?

I have the following

CatsPage.js:

import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
//import * as catActions from '../../actions/catActions';
import CatList from './CatList';
import {loadCats} from '../../actions/catActions';

class CatsPage extends React.Component {
  componentDidMount () {
    this.props.dispatch(loadCats())
  }
  render() {
    return (
      <div>
        <h1>Cats</h1>
        <div>
          <CatList cats={this.props.cats} />
        </div>
      </div>
    );
  }
}

CatsPage.propTypes = {
  cats: PropTypes.array.isRequired
};

function mapStateToProps(state, ownProps) {
  return {
    cats: state.cats
  };
}

export default connect(mapStateToProps)(CatsPage);

catActions.js

import * as types from './actionTypes';
import catApi from '../api/CatsApi';

export function loadCats() {
  return function(dispatch) {
    return catApi.getAllCats().then(cats => {
      dispatch(loadCatsSuccess(cats));
    }).catch(error => {
      throw(error);
    });
  };
}

export function loadCatsSuccess(cats) {
  return {type: types.LOAD_CATS_SUCCESS, cats};
}

I'm getting the following error:

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions. Uncaught Error: Actions must be plain objects. Use custom middleware for async actions. at dispatch (createStore.js:166)

I'm a beginner trying to learn how to use React + Redux. What am I doing wrong that I need to fix to make the dispatch work and loadCats()?

Upvotes: 1

Views: 3031

Answers (1)

Stephen L
Stephen L

Reputation: 2339

There's a chance you didn't properly install/configure your store. It should look something like this:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

Upvotes: 2

Related Questions