1

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.

1

1 Answer 1

2

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;
    });
Sign up to request clarification or add additional context in comments.

3 Comments

now its returns a promise. i thought the then function resolves that issue?
Not really, you will have to resolve the returned promise as well.
@user31529 Once you have a promise, you can never make it synchronous -- all code that depends on it has to be chained off it, either using then or await. The consequence of this is that Userlist has to be made asynchronous too with await, or use then inside of it and chain the code that depends on the users from it (probably ending in a setState call of some sort).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.