1

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.

2 Answers 2

2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed that thunk looks like it will work when we need common methods where we need to access the Redux state. Great info to know. But, my colleague reminded me that there IS JSX that we can render with this. It's the 'submit' button. So, I think that a component would make sense in this instance after all.
1

It should not be a Component because, as you said, there is no visual aspect to it.

Create a new action that does just that and dispatch the action from anywhere you need. This action could check the store to see if the action has already happened and then do nothing (or refresh).

The module that uses import {createStore} from 'redux' creates your store. Import the created store in the action module and use store.getState() to inspect the current state of your store.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.