Actions must be plain objects error with redux-thunk on React SSR

Asked
Active3 hr before
Viewed126 times

7 Answers

plainreduxactionserrorreactobjects
90%

Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.,Here is an example of async action using redux-thunk middleware.,Software Recommendations

This would work:

export function bindComments(postId) {
   return function(dispatch) {
      return API.fetchComments(postId).then(comments => {
         // dispatch
         dispatch({
            type: BIND_COMMENTS,
            comments,
            postId
         });
      });
   };
}
load more v
88%

This error exists because you try to return a non-plain object on a redux action. For example, if you try to return another function, especially an async function, inside this action, redux doesn’t know how to handle this natively.,If you get actions must be plain objects. use custom middleware for async actions error, here is how to fix this issue.,Then setup the middleware on your root redux configuration:

This error exists because you try to return a non-plain object on a redux action. For example, if you try to return another function, especially an async function, inside this action, redux doesn’t know how to handle this natively.

// redux action that returns async function
export const myAction = (payload) => async (dispatch) => {
   // your action
}
load more v
72%

I am trying to resolve this issue. Am new to react.,Here is my offer action,Successfully merging a pull request may close this issue.

import axios from 'axios';

// offers
export const FETCH_OFFERS = 'FETCH_OFFERS';
export const FETCH_OFFERS_SUCCESS = 'FETCH_OFFERS_SUCCESS';
export const FETCH_OFFERS_FAILURE = 'FETCH_OFFERS_FAILURE';
export const RESET_OFFERS = 'RESET_OFFERS';

// offer
export const FETCH_OFFER = 'FETCH_OFFER';
export const FETCH_OFFER_SUCCESS = 'FETCH_OFFER_SUCCESS';
export const FETCH_OFFER_FAILURE = 'FETCH_OFFER_FAILURE';
export const RESET_OFFER = 'RESET_OFFER';

const BASE_URL = location.href.indexOf('localhost') > 0 ? 'http://localhost:9001' : '';

export function fetchOffers(dispatch) {
   const request = axios({
      method: 'GET',
      url: `${BASE_URL}/offers`,
      headers: []
   });

   request.then((response) => {
         dispatch(fetchOffersSuccess(response));
      })
      .catch((err) => {
         dispatch(fetchOffersError(err))
      })

   return {
      type: FETCH_OFFERS,
      payload: request
   };
}

export function fetchOffersSuccess(offers) {
   return {
      type: FETCH_OFFERS_SUCCESS,
      payload: offers
   };
}

export function fetchOffersError(error) {
   return {
      type: FETCH_OFFERS_FAILURE,
      payload: error
   };
}
load more v
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Laravel Vue3 – Passing Token and User info to Vue store

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { persistStore } from 'redux-persist';
import { PersistGate } from 'redux-persist/lib/integration/react';
import { configureStore } from './store';
import {BrowserRouter as Router, Link, Route, Switch} from 'react-router-dom';

import './css/index.css';
import Customer from './Customer';
import Admin from './Admin';

class Index extends Component {
  render() {
    return (
      <Router>
        <Route exact path="/" component={Customer}></Route>
        <Route exact path="/admin" component={Admin}></Route>
      </Router>
    );
  }
}

const store = configureStore();
const persistor = persistStore(store);

ReactDOM.render(
    <Provider store={store}>
        <PersistGate
            loading="<div>Loading...</div>"
            persistor={persistor}>
            <Index/>
        </PersistGate>
    </Provider>,
    document.getElementById('root'));
load more v
40%

(Function) A store enhancer that applies the given middleware. The store enhancer signature is createStore => createStore but the easiest way to apply it is to pass it to createStore() as the last enhancer argument.,To apply multiple store enhancers, you may use compose().,For example, redux-thunk lets the action creators invert control by dispatching functions. They would receive dispatch as an argument and may call it asynchronously. Such functions are called thunks. Another example of middleware is redux-promise. It lets you dispatch a Promise async action, and dispatches a normal action when the Promise resolves.

import {
   createStore,
   applyMiddleware
} from 'redux'
import todos from './reducers'

function logger({
   getState
}) {
   return next => action => {
         console.log('will dispatch', action)
         // Call the next dispatch method in the middleware chain.    const returnValue = next(action)
         console.log('state after dispatch', getState())
         // This will likely be the action itself, unless    // a middleware further in chain changed it.    return returnValue  }}
         const store = createStore(todos, ['Use Redux'], applyMiddleware(logger))
         store.dispatch({
            type: 'ADD_TODO',
            text: 'Understand the middleware'
         }) // (These lines will be logged by the middleware:)// will dispatch: { type: 'ADD_TODO', text: 'Understand the middleware' }// state after dispatch: [ 'Use Redux', 'Understand the middleware' ]
load more v
22%

The simplest React Redux tutorial I wish I had when I started learning. Includes Redux Toolkit!,React Redux tutorial: what is the state?,React Redux tutorial: what you will learn

npx create - react - app react - redux - tutorial
load more v

Other "plain-redux" queries related to "Actions must be plain objects error with redux-thunk on React SSR"