nikotromus nikotromus - 1 year ago 111
React JSX Question

proper react component usage

I have a project that uses React and Redux. I have multiple React components that need to use a common method that will scrape data out of the Redux Store, build a request object and fire off a rest request to the server.

I wouldn't want to write the method that does this more than one time. So, should this method be it's own React component, or should I just put it in a common javascript file? I'm not sure what the point of having a component would be if you're not rendering any JSX. On the other hand, if I put it in a common javascript file, is it possible to wire up redux to that file to get access to the states in the store?

Thanks in advance.

Answer Source

Adding the redux-thunk middleware lets you dispatch functions, which then get access to dispatch and getState(). From there you can do anything you want, such as using selector functions to extract pieces of state that you need, and making AJAX calls. The thunk action creators can be passed to components as props, including binding them to auto-dispatch:

function someThunk() {
    return (dispatch, getState) => {
        const state = getState();

        // do anything you want here

const actions = {doStuffOnClick : someThunk};

export default connect(mapState, actions)(MyComponent);

Further resources:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download