Search code examples
javascriptreactjsreduxreact-reduxes6-promise

Using Promises with React Redux


I'm trying to set my Redux state with some items that depend on an API call.

This is what i have so far.

The Api call ->

return new Promise((resolve, reject) => {
    const _items = [];
    axios.get(SiteUrl + spQuery).then((response) => {
       //console.log(response);
        return response.data.d.results;
    }).then((listItemsData) => {
        ......
        _items.push({...});
        return _items;
    }).then((items) => { 
        resolve(items);
    });
});

And in my componentDidMount() i tried several things, including ->

store.dispatch(addListItem(this.updateSharepointList().then((result) => { return result })));

And

    store.dispatch(addListItem(this.updateSharepointList()));

Both of the calls return the Promise object (with PromiseValue) but if i do it like //let test = this.updateSharepointList().then((result) => { console.log(result) });

And i use console.log(test) it is fine. I get back the array of items.

What am i doing wrong here?


Solution

  • As I understand it the problem is that you are passing a promise to the action creator not the actual value.

    The action creator should be called when you have the items, when the API call is complete and the promise is resolved.

    this.updateSharepointList().then((result) => { 
         store.dispatch(addListItem(result)) 
    })
    

    If you are using react you could checkout "react-redux" you could checkout connect and binding the action creators to your props. Its a more elegant and easier to work with approach.

    Example using react-redux:

    class MyComponent extends Component {
       doSomething() {
         this.updateSharepointList().then((result) => { 
           this.props.addListItem(result);
         })
       }
    }
    
    const mapDipatchToProps = (dispatch) => ({
         addListItem: (listItem) => dispatch(addListItem(listItem))
    )}
    
    const mapStateToProps = (state) => ({}) // used for getting state from store and mapping it to props 
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)