Reputation: 103
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 ?
Upvotes: 3
Views: 819
Reputation: 1061
There is a slight problem in your action. Action creators are functions that return actions. You want to return an action (In this case a function) from your action creator.
So your action shoule be:
export const fetchPosts = () => async (dispatch) => {
// Added this part ^^^^^^
try {
const {data} = await api.fetchPosts()
dispatch({
type: types.FETCH_POSTS,
payload: data
})
} catch (err) {
console.error(err)
}
}
Alternatively, you can make this change to your code:
useEffect(() => {
dispatch(fetchPosts)
// Removed the () ^
}, [dispatch])
Upvotes: 0
Reputation: 12787
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)
}
}
Upvotes: 2
Reputation: 7045
export const fetchPosts = () => async () => await axios.get(url)
the function above returns a promise
try
export const fetchPosts = async () => {
let res = await axios.get(url)
return res;
}
Upvotes: 0