How to use .dispatch in react redux? - reactjs

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 newbie try to learn how to use React + Redux. What am I doing wrong that I need to fix to make the dispatch work and loadCats()?
Thank you!

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)
);

Related

How to fix Uncaught TypeError: Cannot read property 'getState' of undefined?

I am trying to use React with Redux for the frontend part with django rest framework in the backend. Got the issue getState in Provider tag in App component because of issue in store. And when i try to use the map function in the Words.js, I get error of undefined use of map. And I believe this is because of value of the array is null. Hence to fixed this error of getState.
Got this error even on including the store in Provider of App component when a reducers was not defined.
When I load a static array it does get rendered properly in the specific component.
This is Redux Store in the filename:store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import rootReducer from './reducers'
const initialState = {};
const middleware = [thunk];
const enhancer = composeWithDevTools(applyMiddleware(...middleware));
const store = createStore(
rootReducer,
initialState,
enhancer
);
export default store;
The index.js file is below
import App from './components/App'
import ReactDOM from 'react-dom';
import React from 'react';
ReactDOM.render(<App />, document.getElementById("app"));
They action types file types.js using django rest_framework to create the data.
export const GET_WORDS = "GET_WORDS";
The action file words.js
import { GET_WORDS } from "./types";
import axios from 'axios';
export const getWords = () => dispatch => {
axios.get('/api/words/')
.then(res => {
dispatch({
type: GET_WORDS,
payload: res.data
});
}).catch(err => console.log(err));
}
combined reducer file
import { combineReducers } from "redux";
import words from './words';
export default combineReducers({
words
});
The reducer file word.js
import { GET_WORDS } from '../actions/types';[enter image description here][1]
const initialState = {
words: []
}
export default function (state = initialState, action) {
switch (action.type) {
case GET_WORDS:
return {
...state,
words: action.payload
}
default:
return state;
}
}
The Component in which the words list will be called: Words.js
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getWords } from "../../../actions/words";
export class Words extends Component {
static propTypes = {
words: PropTypes.array.isRequired,
getWords: PropTypes.func.isRequired
};
componentDidMount() {
this.props.getWords();
}
render() {
return (
<Fragment>
Hi
</Fragment>
)
}
}
const mapStateToProps = state => ({
words: state.words.words
});
export default connect(mapStateToProps, { getWords })(Words);
And finally the App component
import React, { Component, Fragment } from 'react';
import Footer from './Layout/Footer/Footer';
import Header from './Layout/Header/Header';
import WordsDashboard from './Content/Words/WordsDashboard';
import { store } from '../store';
import { Provider } from "react-redux";
import { Words } from './Content/Words/Words';
export class App extends Component {
render() {
return (
<Provider store={store}>
<Fragment>
<Header />
React Buddy
<Words />
<Footer />
</Fragment>
</Provider>
)
}
}
export default App;
Your initialState has only words prop, so when mapping it to props you have one extra words level. Try changing it to:
const mapStateToProps = state => ({
words: state.words
});
Also you need to use mapDispatchToProps for getWords, since in your current code you're missing dispatch wrapper:
const mapDispatchToProps = dispatch => ({
getWords: () => dispatch(getWords())
})
export default connect(mapStateToProps, mapDispatchToProps)(Words);

How to apply async react redux middleware

I'm a beginner in react.
I'd like to use the react redux to request api.
Error: Actions must be plain objects. Use custom middleware for async actions. An error has occurred.
Please help me with any problems.
I'd like to ask you how redux middleware should be applied.
action/index.js
export const fetchActionMovies = async () => {
const request = await axios.get(`${BASE_URL}/discover/movie?api_key=${API_KEY}&with_genres=28`)
return {
type: FETCH_ACTION_MOVIES,
payload: request
}
}
reducers/reducerActionMovies.js
import { FETCH_ACTION_MOVIES } from '../actions/index';
export default function (state = {}, action) {
switch (action.type) {
case FETCH_ACTION_MOVIES:
const data = action.payload.data.results;
return { ...state, data }
default:
return state;
}
}
container/ActionMovie.jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchActionMovies } from '../store/actions/index';
const ActionMovies = () => {
const dispatch = useDispatch();
const fetch = dispatch(fetchActionMovies());
console.log(fetch);
return (
<div>
<h1>Action Movies</h1>
</div>
)
}
export default ActionMovies;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import ReduxThunk from 'redux-thunk';
import rootReducer from './store/reducers';
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(ReduxThunk))
);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
Error: Actions must be plain objects. Use custom middleware for async actions.
First, even if you're going to use redux-thunk, you need to break up your action into three parts to track the asynchronous state of the request.
const FETCH_ACTION_MOVIES_REQUEST = "FETCH_ACTION_MOVIES_REQUEST";
const FETCH_ACTION_MOVIES_SUCCESS = "FETCH_ACTION_MOVIES_SUCCESS";
const FETCH_ACTION_MOVIES_FAILURE = "FETCH_ACTION_MOVIES_FAILURE";
You should create three actions that use these types that your reducer will track. Now, if you're not going to use redux-thunk... you will need to perform this fetch in your component. However, if you are using redux-thunk you can create an action like this:
export const fetchActionMovies = () => dispatch => {
dispatch(fetchActionMoviesRequest());
return axios.get(`${BASE_URL}/discover/movie?api_key=${API_KEY}&with_genres=28`).then(({
data
}) => {
dispatch(fetchActionMoviesSuccess(data));
}).catch(error => {
dispatch(fetchActionMoviesFailure(error));
})
}
Another option to consider is redux-saga.

React.js Unable to get property 'dispatch' of undefined or null reference

Issue Screen Shot
I am facing 'dispatch' of undefined issue when executing the application.
Whether I need to import any package to work with dispatch in React.js?
ProgramManager.js: This is my component this is where I am using dispatch to call action creator.
import React from 'react';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux'
import {postsActions,postsSelectors} from '../store/userList/index';
class ProgramManager extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
this.fetchPosts({});
}
fetchPosts(params) {
this.context.store.dispatch(postsActions.fetchPosts(params));
}
render() {
return (
<div className="right-container">
....
</div>
) }
}
function mapStatetoProps(state) {
debugger;
return {
//users: state.Users
params: postsSelectors.getParams(state),
posts: postsSelectors.getPosts(state),
};
}
export default connect(mapStatetoProps)(ProgramManager);
Store.js: This is my Redux Root Store file.
import { applyMiddleware, createStore, combineReducers, compose } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
//import { hashHistory } from 'react-router';
import { routerMiddleware } from 'react-router-redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
import rootEpic from './epics';
// const logger = createLogger({ collapsed: true });
const epicMiddleware = createEpicMiddleware();
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
epicMiddleware.run(rootEpic);
export default createStore(
rootReducer,
composeEnhancers(
applyMiddleware(
epicMiddleware,
logger,
// routerMiddleware(hashHistory),
thunk,
)
)
);
epics.js This is my root epic that combines all sub epic files
import { combineEpics } from 'redux-observable';
import { values } from 'lodash';
import * as postsEpics from './userList/epic';
export default combineEpics(
...values(postsEpics)
);
reducer.js This is my root reducer that combines all sub reducers.
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import posts from './userList/reducer';
export default combineReducers({
posts,
routing: routerReducer,
});
epic.js This the sub epic file that actually gets data from the server.
import { keyBy } from 'lodash';
import axios from 'axios';
import querystring from 'querystring';
import { Observable } from 'rxjs/Observable';
import { push } from 'react-router-redux';
import * as actionTypes from './actionType';
import * as postsActions from './actionCreator';
//import * as RequestModel from './request.model';
export function fetchPosts(action$) {
debugger;
alert('fetchPosts');
//RequestModel.entity = "sample";
return action$.ofType(actionTypes.FETCH_COLLECTION)
.map(action => action.payload)
.switchMap(params => {
return Observable.fromPromise(
axios.get(`http://localhost:8081/posts?${querystring.stringify(params)}`)
// axios.get('http://localhost:4040/admin/getTenantUsers')
).map(res => postsActions.fetchPostsSuccess(res.data, params));
});
}
actionCreation.js this is where the disptacher called to get the state data from post
import { keyBy } from 'lodash';
import * as actionTypes from './actionType';
export function fetchPosts(payload) {
debugger;
return { type: actionTypes.FETCH_COLLECTION, payload };
}
export function fetchPostsSuccess(posts, params) {
debugger;
const byId = keyBy(posts, (post) => post.id);
return {type: actionTypes.FETCH_COLLECTION_SUCCESS, payload: {byId, params}};
}
I have never used a context object to dispatch an action.
I think the best way to have an action ready to be dispatched is by using mapDispatchToProps as the second argument of your connect wrapper, it will bring your action as a prop.
import React from 'react';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux'
import {postsActions,postsSelectors} from '../store/userList/index';
class ProgramManager extends React.Component {
componentDidMount() {
this.props.fetchPosts();
}
render() {
return (
<div className="right-container">
....
</div>
) }
}
function mapStatetoProps(state) {
debugger;
return {
//users: state.Users
params: postsSelectors.getParams(state),
posts: postsSelectors.getPosts(state),
};
}
function mapDispatchToProps() {
return postsActions
}
export default connect(mapStatetoProps, mapDispatchToProps)(ProgramManager);
mapDispatchToProps is usually a function that simply returns a javascript object with your action creators like:
{
fetchPosts: postActions.fetchPosts,
...
}
That's why you can even go more direct (and no need to declare a mapDispatchToProps function):
export default connect(mapStatetoProps, postActions)(ProgramManager);
React-Redux provides dispatch when you connect your components. So you don't have to use the store in the context to dispatch actions. You can simply do this.props.dispatch(actionCreator()) within your connected components.
Note that it only provides dispatch to your component if you do not pass your own mapDispatchToProps. i.e., when you do
connect(mapStateToProps)(Component)
// or
connect()(Component)
// and not
connect(mapStateToProps, mapDispatchToProps)(Component)
If you provide mapStateToProps, however, you are expected to specify the action creators and wrap them around dispatch, so you don't need the dispatch for manual dispatches anymore.

Next.js and redux. Populating store on server side does not take effect

I connected redux to Next.js app just like in the docs (not sure what mapDispatchToProps does in the example though):
Init store method:
import { createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import tokenMiddleware from './tokenMiddleware';
import getReducer from './combineReducers';
const logger = createLogger({ collapsed: true, diff: true });
const axiosMw = axiosMiddleware(axios.create(), { successSuffix: '_SUCCESS', errorSuffix: '_FAILURE' });
export default function initStore(logActions) {
return function init() {
const middleware = [tokenMiddleware, axiosMw];
if (logActions) middleware.push(logger);
return createStore(getReducer(), applyMiddleware(...middleware));
};
}
HOC which I use to connect pages:
import 'isomorphic-fetch';
import React from 'react';
import withRedux from 'next-redux-wrapper';
import { setUser } from 'lib/publisher/redux/actions/userActions';
import PublisherApp from './PublisherApp';
import initStore from '../redux/initStore';
export default Component => withRedux(initStore(), state => ({ state }))(
class extends React.Component {
static async getInitialProps({ store, isServer, req }) {
const cookies = req ? req.cookies : null;
if (cookies && cookies.user) {
store.dispatch(setUser(cookies.user));
}
return { isServer };
}
render() {
console.log(this.props.state);
return (
<PublisherApp {...this.props}>
<Component {...this.props} />
</PublisherApp>
);
}
}
);
The problem I'm having is that dispatched action
store.dispatch(setUser(cookies.user));
seems to work fine on server (I've debugged reducer and I know this user object from cookies is indeed handled by reducer) but when I do console.log(this.props.state) I get reducer with initial state - without user data.
You are missing second parameter inside createStore call. Try this:
export default function initStore(logActions) {
return function init(initData) {
const middleware = [tokenMiddleware, axiosMw];
if (logActions) middleware.push(logger);
return createStore(getReducer(), initData, applyMiddleware(...middleware));
};
}
Notice added initData parameter and it's usage.

How to get a resolved promise to my component with Redux Promise?

I'm making a request in my action - pulling from an API that needs to load in some data into my component. I have it start that request when the component will mount, but I can't seem to get Redux-Promise to work correctly because it just keeps returning:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
in my dev tools when I try to console.log the value inside of my componentWillMount method.
Here's my code below:
Store & Router
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(promiseMiddleware)
);
render(
<Provider store={store}>
<Router history={hashHistory} routes={routes} />
</Provider>,
document.getElementById('root')
);
Action
import axios from 'axios';
export const FETCH_REVIEWS = 'FETCH_REVIEWS';
export const REQUEST_URL = 'http://www.example.com/api';
export function fetchReviews() {
const request = axios.get(REQUEST_URL);
return {
type: FETCH_REVIEWS,
payload: request
};
};
Reviews Reducer
import { FETCH_REVIEWS } from '../actions/reviewActions';
const INITIAL_STATE = {
all: []
};
export default function reviewsReducer(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_REVIEWS:
return {
...state,
all: action.payload.data
}
default:
return state;
}
}
Root Reducer
import { combineReducers } from 'redux';
import reviewsReducer from './reviewsReducer';
const rootReducer = combineReducers({
reviews: reviewsReducer
});
export default rootReducer;
Component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchReviews } from '../../actions/reviewActions';
class Home extends Component {
componentWillMount() {
console.log(this.props.fetchReviews());
}
render() {
return (
<div>List of Reviews will appear below:</div>
);
}
}
export default connect(null, { fetchReviews })(Home);
Any and all help is greatly appreciated. Thank you.
Redux-promise returns a proper Promise object, so you may change your code a little bit to avoid immediate execution.
class Home extends Component {
componentWillMount() {
this.props.fetchReviews().then((whatever) => { console.log('resolved')})
}
// ...
}

Resources