0

Help to understand what the problem is. When I write mapDispatchToProps like this:

const mapDispatchToProps = (dispatch: any) => {
    return {
        getPostByIdAction: (post: any) => dispatch ({type: GET_ID, payload: post})
    }
};

everything is working fine. But when I try to dispatch the function in this way:

const mapDispatchToProps = (dispatch: any) => {
    return {
        getPostByIdAction: (post: any) => dispatch (getPostById (post))
    }
};

I get an error: Actions must be plain objects. Use custom middleware for async actions. What could have gone wrong?

my actions:

export const getPostById = async (id: any) => {
    const myResponse = await fetch (`https://jsonplaceholder.typicode.com/posts/$ {id}`);
    const myJson = await myResponse.json ();
    const post = myJson.body
}

my reducer:

import {combineReducers} from 'redux'
import {pageReducer} from './page'


export const rootReducer = combineReducers ({
  page: pageReducer
})
import {GET_ID} from '../actions/PageActions'

const initialState = {
    post: "Click on article to read it"
}

export function pageReducer (state = initialState, action: any) {
    switch (action.type) {
        case GET_ID:
            return {... state, post: action.payload};
        default:
            return state
    }
}
1
  • I suggest you to use redux-thunk or redux-saga instead of creating a custom middleware for this.
    – Andus
    Feb 9, 2020 at 12:57

2 Answers 2

0
export const getPostById = async (id: any) => {
    const myResponse = await fetch (`https://jsonplaceholder.typicode.com/posts/$ {id}`);
    const myJson = await myResponse.json ();
    const post = myJson.body
}

you are not returning anything. you should return an object here to pass it to dispatch. dispatch needs an object and that object has to have "action" property. you can add more properties but "action" property is a must.

0

The main problem with redux is that.., it is synchronous. To handle async operations, we use middlewares. There are many libraries available to handle async operations.

But, if you want to create one, lets create a custom middleware for async operations

I've defined some types for type safety (since we're doing it in typescript). Here we added another field 'api' for our convenience to differentiate the async operations with non-async ones

import { Middleware, Dispatch, MiddlewareAPI } from 'redux'


export interface DispatchType {
    type: string
    payload?: any
    meta?: DispatchMeta
}

export interface DispatchMeta {
    async: boolean
    api: {
        url: string
        onComplete: string
        // extra information you want for the request can be passes here:
        // eg
        // params, method, data
    }
}

The object type that we dispatch looks something like this:

dispatch({type: 'TYPE_OF_DISPATCH', payload: 'any type of payload'})

Now lets create the Middleware to intercept those actions(object) that has meta field with async set to 'true'.


// Middleware to intercept those actions(object) that has meta field with async set to true;

export const asyncMiddleware: Middleware = ({ getState }: MiddlewareAPI) => (
    next: Dispatch
) => async (action: DispatchType) => {


    // Call the next dispatch method in the middleware chain.
    next(action);

    if (action.meta && action.meta.async && action.meta.api) {
        const res = await fetch(action.meta.api.url);
        const json = await res.json();
        const post = json.body;
        next({
            type: action.meta.api.onComplete,
            data: post
        })
    }


}

Here our middleware intercepts the action with async flag 'true' and then once completed, its dispatches the 'onComplete' action sent to the meta.

To use this middleware, Your dispatch action should look something like this

dispatch({
  type: 'FETCH',
    meta: {
        async: true,
        api: {
            url: 'https://jsonplaceholder.typicode.com/posts/1',
            onComplete: 'FETCHED_POST'
        }
    }
})

Here you may create a wrapper function which dispatches the above action

const getpost = (id: string) => 
   dispatch({
          type: 'FETCH',
            meta: {
                async: true,
                api: {
                    url: `https://jsonplaceholder.typicode.com/posts/${id}`,
                    onComplete: 'FETCHED_POST'
                }
            }
        })   

Lastly, don't forget to apply the middleware to your redux store.

const store = createStore(
    RootReducer,
    applyMiddleware(asyncMiddleware)
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.