Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 473
Cihan Özcan Avatar asked May 29 '26 09:05

Cihan Özcan


1 Answers

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)
    }
}
like image 59
Viet Avatar answered Jun 04 '26 21:06

Viet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!