AnApprentice
AnApprentice

Reputation: 111070

How to access the store in React components?

I'm working off the react-redux example here: https://github.com/timscott/react-devise-sample

The redux store is being created in setup.js like so: https://github.com/timscott/react-devise-sample/blob/master/client/src/app/setup.js

key part:

const initStore = ({onRehydrationComplete}) => {
  store = createStore(
    combineReducers({
      ...reactDeviseReducers,
      cats: [],
      form: formReducer,
      router: routerReducer,
      apollo: apolloClient.reducer()
    }),
    {},
    compose(
      applyMiddleware(
        thunk,
        routerMiddleware(history),
        apolloClient.middleware()
      ),
      autoRehydrate()
    )
  );

  persistStore(store, {
    blacklist: [
      'form'
    ]
  }, onRehydrationComplete);

  return store;
};

Outside of this file in a react component: CatsPage.js

I'm trying to .dispatch(loadCats()) so the react app will fetch the list of cats from the server, update the store, and react magically update the dom. Here is what I have in CatsPage.js:

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

class CatsPage extends React.Component {
  state = {
    rehydrated: false
  };
  componentDidMount() {
    initStore.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);

I'm getting the error: Uncaught TypeError: _setup.initStore.dispatch is not a function

I'm a react-redux beginner.

Update

CatList.js

import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';

const CatList = ({cats}) => {
  return (
      <ul className="list-group">
        {cats.map(cat =>
           <li className="list-group-item" key={cat.id}>
            <Link to={'/cats/' + cat.id}>{cat.name}</Link>
           </li>
        )}
      </ul>
  );
};

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

export default CatList;

Upvotes: 0

Views: 1292

Answers (1)

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

I assume that you have setup your Provider correctly. If so correct way to access dispatch method is props. So you can do something like this.

this.props.dispatch(loadCats())

Upvotes: 1

Related Questions