score:2

Accepted answer

Sorry, i will answer my own question:

i change this:

const mapDispatchToProps = dispatch => {
  return {
    fetchOneCategory: slug => {
      dispatch(fetchOneCategory(slug)).then(() => {
        console.log('working');
      });
    },

  };
};

to

const mapDispatchToProps = dispatch => {
  return {
    fetchOneCategory: slug => {
      return dispatch(fetchOneCategory(slug))
    },
  };
};

and now i can make this:

import React from 'react';
import { connect } from 'react-redux';

class MyComponent extends React.Component {

  componentDidMount() {
    this.props.fetchOneCategory()
      .then( () => { console.log('it works'); })
      .catch( () => { console.log('on error'); });
  }

  render() {
    return ( <p>Whatever</p> );
  }
}

thanks for your help!

score:0

in your container, you don't need

.then(() => {
    console.log('working');
  });

dispatch(fetchOneCategory(slug)) doesn't return a promise, there is no then to be read

score:3

Here's how I am approaching this.

First, there are a couple of changes you need to do to your subCategoriesFetchData function:

export const subCategoriesFetchData = (page = 1, parentOf) => {
  return dispatch => {
    dispatch(oneCategoryLoading(true));

    // That's the key thing. Return a new promise, then ma
    return new Promise((resolve, reject) => {

      api.categoriesFetchData(page, parentOf)
        .then(response => {
          dispatch(subCategoriesFetchDataSuccess(response.data.results));
          dispatch(oneCategoryLoading(false));

          resolve(response); // Resolve it with whatever you need
        })
        .catch(error => {
          console.log(error);

          reject(error); // And it's good practice to reject it on error (optional)
        });
    });
  };
};

Then, here's how you can do the trick with mapDispatchToProps and then chaining .then()s:

import React from 'react';
import { connect } from 'react-redux';
import { subCategoriesFetchData } from './wherever-it-is';

class MyComponent extends React.Component {

  componentDidMount() {
    this.props.subCategoriesFetchData()
      .then( () => { console.log('it works'); })
      .catch( () => { console.log('on error'); });
  }

  render() {
    return ( <p>Whatever</p> );
  }
}

const mapDispatchToProps = { subCategoriesFetchData };

connect(null, mapDispatchToProps)(MyComponent);

Related Query

More Query from same tag