In the newest versions of Axios, you are returned a response object containing the data or an error object containing an error object. response.data gives you the information you are looking for along with response.status or response.statusText. The entires object consists of:
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {}
}
The error object can be obtained through a .catch(error) attached to the promise. In your case, I would do:
Hey, i put this one up because i cant find a solution for this Problem:
getUsers() {
let list = {};
axios.get('users').then(function (result) {
console.log(result); // as in all examples it works well here, but it is not very helpful
list = result.data; // LIST = , OR RETURN - no idea how to set list
});
return list;
};
@alanaasmaa thank you for your answer - Here is more context:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export default class Users extends Component {
constructor(props) {
super(props);
this.title = "Users";
this.users = this.getUsers();
}
getUsers() {
let list = {};
axios.get('users').then(function (result) {
console.log(result);
list = result.data;
});
return list;
};
render() {
...
The problem I have is that i can't access the area outside of the .then (function () { ... }) ( same on doSomething() ) - so, maybe it's a logic mistake by me, but so the only thing i can do is something like console.log() -> but how can set some Object Properties (
irrespective of react) with get Data? Have you or anyone else a cool way? Thanks!
@thomas_ilspa well the way you do it is not the "React Way" you can't just simply mutate state properties in React, and you don't even use a state? Anyway I "refactored" your code see below that should worrk!
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export default class Users extends Component {
// this method fires off before anything gets rendered
// just search for react lifecycle methods and you will understand what i mean
componentWillMount() {
getUsers();
}
constructor(props) {
super(props);
this.title = "Users";
// this.users = this.getUsers(); // THIS IS WRONG
this.state = {
users: []
}
}
// getUsers() {
// let list = {};
// axios.get('users').then(function (result) {
// console.log(result);
// list = result.data;
// });
// return list;
// };
// I like to use arrow syntax functions
getUsers = () => {
axios.get('users')
.then( (response) => {
this.setState({users: response.data});
})
.catch( (error) => {
console.log(error);
});
}
render() {