Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling ajax with React

How should I handle ajax requests in a fairly traditional web application? Specifically with using React for views, while having a backend that handles data such as text and what not, but using ajax to automatically save user interactions such as toggling options or liking a post to the server.

Should I just use jQuery for this, or would something like Backbone be more beneficial?

like image 729
user2442241 Avatar asked May 01 '15 16:05

user2442241


People also ask

Can we use AJAX with React?

You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.

How does AJAX work in react JS?

APIs are used for fetching data from the server and using AJAX and API we call data asynchronously and show it in our HTML. You can make API requests by using browser build in fetch function or third party libraries like Axios.

Where can you initiate your AJAX requests in React?

In this method, we initiate the AJAX request using XMLHttpRequest . We use the GET method and https://programming-quotes-api.herokuapp.com/quotes/page/1 as the endpoint which returns a JSON output of first page quotes. readystatechange handler is called when the readyState of the request changes.


1 Answers

Just in case anybody stumbled upon this and does not know, jQuery makes it super easy to send AJAX calls. Since React is just JavaScript it will work just like any other jQuery AJAX call.

React's own documentation uses jQuery to make the AJAX call so I assume that's good enough for most purposes regardless or stack.

componentDidMount: function() {     $.ajax({       url: this.props.url,       dataType: 'json',       cache: false,       success: function(data) {         this.setState({data: data});       }.bind(this),       error: function(xhr, status, err) {         console.error(this.props.url, status, err.toString());       }.bind(this)     });   }, 
like image 197
PythonIsGreat Avatar answered Sep 18 '22 13:09

PythonIsGreat