ReactJs - How to run AJAX calls?

0

I'm developing a project in React (the first time I'm working with React ) and I'm having doubts when running calls to the server, either GET or POST .

I even managed to perform this task, but in a somewhat "limited" way, because I'm not able to send more complex date structure, such as a JSON object.

I'm currently using fetch() , like this:

// 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, running a POST I can only do this:

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 a JSON object, if it uses it it presents an error and does not execute the call.

Is there any other method, or a correct / best method to execute these calls with React ? It does not have to be with fetch , I'm only using this method because I could not find another one.

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

    
asked by anonymous 01.04.2017 / 21:10

1 answer

0

Despite recommendations for using the fetch method, I opted to use another AJAX call service, due to compatibility issues and promise usage. The service I'm using is the axios that was extremely easy to integrate into the project and has very simple usage.

All I needed to do was download the service, done through npm, and import into the required 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
    })
);
    
10.04.2017 / 00:41