V
V
Valery Chupurnov2017-02-02 11:56:44
JavaScript
Valery Chupurnov, 2017-02-02 11:56:44

React + Redux when to send an AJAX request?

Hello.
There is some application in which the user creates an order. fills in a bunch of different fields, but there is no Order button . Instead, as soon as the form is completely filled, an automatic ajax request should be sent to the server, and the price is shown.
I use redux , so there are no problems when filling out the form, for autocompletion I call ajax requests in actions, and according to the result I shoot the server response reducer. The reducer manipulates the information and state and the component renders the view.
Only the reducer knows that the form is completely and correctly filled out. He has data, he can check all fields. He can tell the component to show the button - Order, in this case.
But after all, the reducer cannot cause an AJAX request to be sent in my version ?!
Well, the only thing that comes to mind is a certain field in which the reducer will write true, and the component will already launch some kind of action on onComponentDidUpdate , is such a scheme normal?
Some kind of circle will turn out, where the component will be drawn once again without the need for it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2017-02-02
@skoder

For redux, the normal scheme. To avoid unnecessary renderings, you need to use shouldComponentUpdate , and send the request from componentWillReceiveProps. It can be seen like this:

componentWillReceiveProps(nextProps) {
  if (nextProps.complete && !this.props.complete) this.sendRequest();
}

shouldComponentUpdate(nextProps) {
  const changed = Object.keys(nextProps).filter(e => nextProps[e] !== this.props[e]);
  if (changed.length == 1 && changed[0] == 'complete') return false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question