Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending ajax request with state data when state changes

I have a react component, In which I am using a date picker. Based on value of Date selected I am sending an ajax request to fetch data. I am not using any frameworks like redux or flux.

export default class MyComponent extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        // Initial fetch request based on the default date
    }

    onDateSelectionChanged(fromDate, toDate) {
        this.setState({
            fromDate,
            toDate
        });
    }

    render() {
        return (
            <div className="row">
                <DateRangePicker callBackParent = {this.onDateSelectionChanged}/>
                {/* other stuff */}
            </div>
        );
    }
}

Now suppose I changed the date to another date. What is the best way to fetch the data again? should I fire request again inonDateSelectionChanged or is there any life-cycle method?

like image 536
WitVault Avatar asked Feb 29 '16 14:02

WitVault


3 Answers

I strongly suggest to decouple the ajax logic from your component. Remeber that plain React was build only to simplify the rendering of the views and not for complex logic like Http calls.

Using Flux you can quickly create the infrastructure for handling both the UI rendering and any other logic for your app.

The complete tutorial is here but I will add a quick summary so that you could easily get started.

Add 4 classes that will be your infrastructure:

  1. YourComponentActions - this class will handle the "actions" that your component will fire. An action is actually an event that will be fired from your component to something that will perform the actual logic (point 4).
  2. SharedConstans - this class will hold the event names of your app.

  3. AppDispatcher - this class will manage the event handling of your app.

  4. YourComponentStore - this class will register to the action's event and handle the http call. Here is the logic of your component that is decoupled from the UI. After you receive a response from your ajax call you will fire another event from your store and your component will register to it and only then update the state.

It feels complex however from now on you will easily add any logic to your app while keeping it decoupled, readable and easy to maintain. Read more about Flux here.

like image 64
Dennis Nerush Avatar answered Oct 21 '22 15:10

Dennis Nerush


You should fire another network request in onDateSelectionChanged, there's no lifecycle method for when state changes.

Technically speaking you could do some logic in componentWillUpdate (or worse, shouldComponentUpdate) to make a request when that state field changes and it would work, but you shouldn't. Both of those lifecycle methods have well defined purposes, making network requests would make your code less clear and harder to maintain.

like image 44
Carl Vitullo Avatar answered Oct 21 '22 14:10

Carl Vitullo


If you really insist on sending the request from your component method, than firing it in onDateSelectionChanged is definitely the way to go. As it responds to every Date change, it is naturally the only method capable of fulfilling your needs, and the lifecycle methods are not directly aware of the Date change nor the right place to do it. Implementing something like that in e.g. componentWillUpdate or componentDidUpdate can possibly lead to cyclic execution and that isn't something you want to face without a good reason.

Speaking of lifecycle methods, the only one explicitly recommended to fire requests is componentDidMount method, where you have a good opportunity to do some ajax initialization operations, as you can see in docs, but none of them is suitable for ordinary data fetching.

On the other hand, I suggest you really have a look at Flux, which is an architecture solving many issues, separation of concerns is on of them. Your problem here is that you tie your component to creation of Ajax requests, which doesn't promote reusability and makes your code harder to maintain. Think of components as tools to present content and capture users inputs, bothering with requests and response or processing and storing incoming data shouldn't be their concern (at least at larger scale).

You can of course separate your request creators to external functions, but if you tend to write React frontend, you will sooner or later face problems like handing props over many intermediary components or propagating events up through your component hierarchy, which is very tedious and messy without some kind of architecture, and Flux is the best solution for these issues and therefore number one technology to learn - if you mean it with React seriously.

like image 44
Skocdopole Avatar answered Oct 21 '22 16:10

Skocdopole