user31529
user31529

Reputation: 43

Axios Returning Undefined

I have the following code:

//agent.js
    import axios from 'axios';
    
    axios.defaults.baseURL = 'https://localhost:5001/api';
    
    const requests = {
      createUser: (payload) => {
        axios.post('/users/create', payload);
      },
      getUsers: () => {
        axios.get('/users').then((r) => {
          console.log(r.data); //outputs the json response
          return r.data;
        });
      }
    };
    
    const agent = {
      requests
    };
    
    export default agent;

//reactComponent.js

import agent from './agent';
function Userlist() {
  const users = agent.requests.getUsers();
  console.log(users); //outputs undefined
}

What am I doing wrong as I get an undefined when making the request from my reactComponent.js.

Upvotes: 1

Views: 1706

Answers (1)

kennysliding
kennysliding

Reputation: 2987

Because you are not returning anything in your getUsers function.

getUsers: () => {
    axios.get('/users').then((r) => {
      console.log(r.data); //outputs the json response
      return r.data;
    });
}

Remove the function bracket and it should work,

getUsers: () => 
    axios.get('/users').then((r) => {
      console.log(r.data); //outputs the json response
      return r.data;
    });

Upvotes: 2

Related Questions