How to get raw data using react-redux connection

I am reading the doc here https://github.com/reactjs/react-redux/blob/master/docs/api.md

I would like to use the Stateless component as much as possible, but I cannot figure out how I would use the raw data payload. With a Stateful React component, my container and component would look like:

// Container
const mapDispatchToProps = (dispatch) {
    return {
        fetchData: () => dispatch(fetchDataAction());
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

// Component
class MyComponent extends React.Component {
    componentDidMount() {
        this.props.fetchData();
    }
}

      

Where does the logic go componentDidMount

if I make my component stateless?

I've seen examples where they suggest you extend your stateless component in a container with Stateful React and add this logic there:

// Container
class MyComponentContainer extends MyComponent {
    componentDidMount() {
        this.props.fetchData();
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(MyComponentContainer);

      

But is this the best way to do it? If I'm trying to build Stateful React, why not just do it right on MyComponent

?

EDIT Just to be clear; I ask if I can basically load my raw data WITHOUT SAVING React.Component

anywhere.

+3


source to share


2 answers


Related to your main question: yes, it is entirely possible to load data as soon as yours is created store

. Just use store.dispatch

from anywhere in your code even outside React.Components

.

You can check out a simple example here . As you can see, the components and data loading process are completely separate from each other.



But is this the best way to do it? If I'm trying to build Stateful React, why not just do it directly on MyComponent?

Indeed, I see no reason to do anything like what you provided in the snippet. Moreover, inheriting your Components from anything else besides React.Component

is definitely a smell in the React world.

+1


source


you can dispatch the action to mapDispatchToProps, but this is a dirty way and is not recommended at all.

const mapDispatchToProps = (dispatch) {
    dispatch(fetchDataAction());
    return {
    }
}

      

But now mapDispatchToProps won't be clean as a side effect. The correct solution is to have a container component that will be linked in the React Component state and dispatch the action to Mount.

Another solution might be if you are using react-redux-router

then:



Note: Should mapDispatchToProps dispatch initialization operations?

Eidt: similar question How to dispatch a Redux action from a stateless component on route load?

0


source







All Articles