Reactjs - How to run AJAX calls?

Asked

Viewed 2,264 times

1

I’m developing a project in React (first time I’m working with React) and I’m having doubts at the time of running calls to the server, be a GET or POST.

I even managed to perform this task, but in a sort of "limited" way, because I am not able to send more complex date structure, as an object JSON.

I am currently using fetch(), thus:

// Funcionando normalmente dentro do esperado
fetch(DEFAULT_URL)
.then(function(response) {
    if ( response.status !== 200 ) {
        console.log('Status Code: ' +  response.status);
        return;
    }

    response.json().then(function(data) {
        console.log(data);
    });
})

However, when executing a POST I only get it this way:

fetch(POST_URL, {
    method: 'POST',
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "name= Nome completo"
})
.then(function(response) {
    if ( response.status !== 200 ) {
        console.log('Status Code: ' +  response.status);
        return;
    }

    response.json().then(function(data) {
        console.log(data);
    });
})

What does not allow sending an object JSON, if using it shows error and does not execute the call.


Is there any other method, or a correct/better method of executing these calls with React? Doesn’t have to be with fetch, I’m only using this method because I couldn’t find another.

The objective would be to obtain data from the database, such as news posts, company data, etc. As well as sending information to register in the database, as well as user registration, among others.

  • I use the method $.ajax jQuery or the shorthands get, post, put and delete. When in doubt, change Ajax library or do some functions on the same arm. Ah! And React has no specific method, but it’s good practice to include calls like this in componentDidMount.

  • @Daniel I intend to continue only using React (or some plugin for it). I don’t intend to load jQuery only to execute ajax calls. Any other suggestions? About where to place calls I’ve read some materials that guide to this.

  • So I think it’s super valid to create simple functions using Xmlhttprequest logo. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

  • Or: instead of sending a JSON object, send only one string using the JSON.Stringify in the object you want to send.

1 answer

1


Despite recommendations regarding the use of the method fetch, I have chosen to use another AJAX call service due to compatibility and use of promise. The service I’m using is the Xios which was extremely easy to integrate into the project and has a very simple use.

All I had to do was download the service, done through npm, and import into the necessary components, for example:

import axios from "axios";

// Método GET
axios.get('/minha/url').then(function (response) {
    console.log('Success: ', response);

}).catch(function (error) {
    console.log('Error: ', error);
});

// Método POST
axios.post('/minha/outra/url', data).then(function (response) {
    console.log('Success: ', response);

}).catch(function (error) {
    console.log('Error: ', error);
});

// Múltiplas requisições
function carregaUsuario() {
    return axios.get('minha/url/usuario');
}

function carregaEndereco() {
    return axios.get('minha/url/endereco');
}

axios.all([carregaUsuario(), carregaEndereco()]).then(
    axios.spread(function (usuario, endereco) {
        // Retorno das requisições
    })
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.