Hello world! I’ve just want to write a short article to speak about Ajax use case with React.
React doesn’t provide features to make Ajax calls like jQuery. The React’s philosophy is to manage UI components by functions and by class (as defined in ES6) using properties and local states. React doesn’t do nothing else. React render and refresh components according to some conditions, each component have a life cycle and developers have to program handlers to lift states and program interactions between components through Virtual DOM.
To respect this principle, for me, a React component shouldn’t have any Ajax functions. Like the example below.
This stupid example have to display articles from a simple blog using a stupid fictive REST API. But i’m doesn’t agree with my own code. The react component shouldn’t have the Ajax function’s declaration. (with fetch)
- Firstly, it’s not in React’s Philosophy to have explicit Ajax calls.
- Secondly, we have to refactor the ajax call, the function must be thought to be used by many components if you want to use it again.
So, let’s see a method to organize this code. Firstly, create a folder call ajax (an explicit name ^^) and create a file named index.js. Put all your ajax functions in this file. With our example, we have to create a function, called GET_articles (by example, i like to write the first letters in Uppercase, the first letters have to describe the method used, GET, POST, PUT ect, it’s my convention, you can anything)
And now, the Ajax function
But i’ve an another problem, to mutate the state i pass the context reference to the function. This solution is pretty bad, for 2 reasons:
- Secondly, if the state properties are not exactly the same, this function cannot works.
The solution ? Use the power of callback !
And the main file
That’s all for this little draft, thx for reading and see you soon for an another exchange of knowledge :)
NB: I haven’t test the code, but it seems correct for me.