Search code examples
reactjsreduxredux-thunk

useEffect dispatch problem (you may need to add middleware)


API

import axios from "axios"

const url = "http://localhost:5000/posts"

export const fetchPosts = () => async () => await axios.get(url)

export const createPost = async (post) => await axios.post(url, post)

ACTION

export const fetchPosts = async (dispatch) => {
    try {
        const {data} = await api.fetchPosts()
        dispatch({
            type: types.FETCH_POSTS,
            payload: data
        })
    } catch (err) {
        console.error(err)
    }
}

STORE

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

export default function configureStore() {
    return createStore(rootReducer, applyMiddleware(thunk))
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import configureStore from './Redux/store/configureStore'

const store = configureStore();

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

I want to make get request to my posts by axios. There is no problem in post request but I can't get one.

useEffect(() => {
    dispatch(fetchPosts())
  }, [dispatch])

When I use this method it throws this error :

Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.

There is no any syntax or import/export mistake.

Why even if I inserted redux thunk to store it throws me this middleware error ?


Solution

  • You need to update fetchPosts return a function

    export const fetchPosts = () => async (dispatch) => {
        try {
            const {data} = await api.fetchPosts()
            dispatch({
                type: types.FETCH_POSTS,
                payload: data
            })
        } catch (err) {
            console.error(err)
        }
    }