Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alanaasmaa's avatar

Get data out from axios ? (JAVASCRIPT)

Hello,

i just cant figure out how could i get the data out of axios ?

createAlbum: function(event) {
    var data;
    event.preventDefault();
    axios.get('/admin/gallery/albums/create')
        .then(function(response, data) {
            data = response.data;
        });
    console.log(data);
}

I got it out once by exporting it to object and saving it.

Example

var gallery = {
    createAlbum: function(event) {
        event.preventDefault();
        axios.get('/admin/gallery/albums/create')
            .then(function(response, data) {
                gallery.data = response.data;
            });
    }
}

But this does not feel the right way to save the request like that ?

0 likes
7 replies
ejdelmonico's avatar

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:

createAlbum:  function(event) {
   event.preventDefault();
   axios.get('/admin/gallery/albums/create')
      .then(function(response) {
         console.log(response.data);
      }).catch(function(error) {
         console.log(error.response.data);
      });
}
2 likes
alanaasmaa's avatar

@ejdelmonico I know that, but i mean how could i use it outside function(response).

If i just console.log it i cant access it outside. Right now im doing it like that

createAlbum: function(event) {
    event.preventDefault();
    if (typeof gallery.createAlbumPage == 'undefined') {
        axios.get('/admin/gallery/albums/create')
        .then(function(response, data) {
            gallery.createAlbumPage = response.data;
            openCreateAlbum();
        });
    } else {
        openCreateAlbum();
    }
    function openCreateAlbum() {
        vex.open({
            unsafeContent: gallery.createAlbumPage,
            contentClassName: 'popup'
        });
    }
}
thomas_ilspa's avatar

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;
    };

Thanx!

alanaasmaa's avatar

@thomas_ilspa Maybe u could try something like this ?

getUsers() {
    axios.get('/users').then(function (result) {
        doSomething(result.data);
    });
}

doSomething(data) {
    console.log(data);
}

Also i would recommend to handle failed requests and do some validation to data.

thomas_ilspa's avatar

@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's avatar

okay, for react i've got it:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

export default class Users extends Component {

    constructor(props) {
        super(props);

        this.state = {
            title: "Users",
            users: []
        };
    }

// !!! This one:
    componentDidMount() {
        axios.get('users')
            .then(res => {
                const users = res.data;
                this.setState({ users });
            });
    }
// !!! https://facebook.github.io/react/docs/react-component.html

    render() {

        console.log(this.state.users)

        return (
            <div>
                <h1>{this.state.title}</h1>
                <ul>
                    {
                        this.state.users.map(
                            user => <li>{user.name}</li>
                        )
                    }
                </ul>
            </div>
        );
    }
}

if (document.getElementById('users')) {
    ReactDOM.render(<Users/>, document.getElementById('users'));
}

andreasbakir's avatar

@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() {

Please or to participate in this conversation.