Skip to content Skip to sidebar Skip to footer

Redux Thunk Fetch Return Undefined

I'm new with Redux Thunk and I'm having problems with dispatch an action after fetching async call by click on button component. actions.js import fetch from 'isomorphic-fetch' ex

Solution 1:

You forgot to return res.json() in actions.js for the next then block. it should be

exportconst loadPosts () => {
return(dispatch) => {
    returnfetch('https://jsonplaceholder.typicode.com/posts')
        .then(res => {
            return res.json();
        }).then(json => {
            dispatch(getPosts(json))
        })
      }}

or you can skip the return statement by removing the blocks by writing .then(res => res.json())

Solution 2:

I the same issue and found that ensuring the thunk middleware was first in my chain when creating the redux store allowed me to access the promise I was after rather than getting undefined,

store = createStore(
            rootReducer, 
            initialState,
            applyMiddleware(thunk, otherMiddleware1, otherMiddleware2)
        );

Solution 3:

mapDispatchToProps should be like this:

function mapDispatchToProps(dispatch) {
return {
    // loadPosts instead of loadPosts()
    loadJsonPosts: () => { dispatch(loadPosts) }
} }

Post a Comment for "Redux Thunk Fetch Return Undefined"