Quantcast
Channel: Better approach to get store data without direct access - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Better approach to get store data without direct access

$
0
0

Let's assume that store have data like this:

{  filter: {    id: 'John Doe'  },  page: 1,  pageSize: 10}

I want to get data from server with those values.

I can achieve this by using React-Redux's connect method:

const mapStateToProps = state => ({  filter: state.filter,  page: state.page,  pageSize: state.pageSize});@connect(mapStateToProps)class SomeComponent extends Component {  getData() {    const { filter, page, pageSize } = this.props;    fetch(...);  }}

In getData() method, I can access those properties by connecting it.

It works fine, however it goes wrong when I try to update those variable before get data, situation like search, and it doesn't work.

search(newFilter) {  dispatch(setFilter(newFilter));  this.getData();}

Note that search is a method that accept key-value object when user submit the search form.

This will not work, because it loads data from server before filter value is change by dispatch.

To solve this, I have to wait until filter updated and passing through as new prop, however there's no way to wait until filter is changed.

Other option could be access store's state directly, like state = store.getState(), however I heard that store must not be exported, because state in store must be updated by actions, not directly updated, even I do not touch the store's state, it's dangerous way. So I want to solve without direct accessing the store.

Is there a way to other solutions to get store's data, not coming from props(because it's too late) but not also direct access to store?

Using connect can't get latest data that just dispatched.

Or, is there a better approach for all this functionalities?

Any advice will very appreciate it!


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>