Javier
Javier

Reputation: 2095

How to make dispatch with redux-thunk with axios

First, apologize for my english.

I'm trying to make a request with redux-thunk.... I dont understan it well.

My idea is make a request using axios but method return undefined before return value of request.

I dont know if I'm passing dispatch well.

Can you help me please? What am I doing wrong???

This is how use dispatch in my component:

....

const mapDispatchToProps = dispatch => {
    return {
        createCustomersGeoJSON: () => dispatch(createCustomersGeoJSON()),
        getAdvicesData: hierarchy => dispatch(getAdvicesData(hierarchy)),
        getSocialNetworkData: () => dispatch(getSocialNetworkData()),
        dispatch,
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(CustomersWidget));

In actions I do this:

export const getSocialNetworkData = () => {
    return dispatch => {
        dispatch({
            type: GET_SOCIAL_NETWORK_DATA,
            payload: fetchSocialNetworkData(),
        });
    };
};

And this is the code of fetchSocialNetworkData function:

axios
    .get(`http://localhost:5000/socialRoute`)
    .then(data => {
        let response = Object.assign({}, data);
        if (
            response &&
            response.data &&
            response.data.tweets &&
            Array.isArray(response.data.tweets)
        ) {
            console.log("data.tweets: ", response.data.tweets);
            return response.data.tweets;
        }
        return [];
    })
    .catch(error => {
        console.log("Error gettin data from socialRoute: ", error);
    });

Upvotes: 1

Views: 186

Answers (1)

liamgbs
liamgbs

Reputation: 5510

It's because you think you're returning the response but what you're actually returning is nothing because you've handled the result of the promise in a .then chain.

You have two options:

Return a promise and resolve it in the .then:

function fetchSocialNetworkData() {
    return new Promise((resolve) => {
        axios
            .get(`http://localhost:5000/socialRoute`)
            .then(data => {
                let response = Object.assign({}, data);
                if (
                    response &&
                    response.data &&
                    response.data.tweets &&
                    Array.isArray(response.data.tweets)
                ) {
                    console.log("data.tweets: ", response.data.tweets);
                    resolve(response.data.tweets);
                }
                resolve([]);
            })
    })
}

OR

Use async/await (the modern way)

async function fetchSocialNetworkData() {
    const data = await axios.get(`http://localhost:5000/socialRoute`);

    let response = Object.assign({}, data);
    if (
        response &&
        response.data &&
        response.data.tweets &&
        Array.isArray(response.data.tweets)
    ) {
        console.log("data.tweets: ", response.data.tweets);
        return response.data.tweets;
    }
    return [];
}

Both of these are the same thing under the hood. IE they're both different ways of writing a promise.

Now. in your thunk, you're still just calling that function, which means you're going to get the unresolved promise rather than the result of that promise. So the thunk becomes:


export const getSocialNetworkData = () => {
    return async (dispatch) => {
        dispatch({
            type: GET_SOCIAL_NETWORK_DATA,
            payload: await fetchSocialNetworkData(),
        });
    };
};

The thing to take away from this is that you can get far without understanding promises but that lack of understanding will always be a ceiling for your JS skills.

Upvotes: 2

Related Questions