user2794166
user2794166

Reputation: 11

Return response from Axios and assign it to a variable

I'm trying to get something simple done with Axios but no luck. I want to get a response back from Axios call and assign it to a variable and do something with it next outside of the function block.

const axios = require("axios");
var posts;
(async () => {
  const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
  posts = allPosts;
})()
// do something with posts here

I know because the func is async we get to // do something with posts here first but then how we can work with the response outside of async function

Upvotes: 1

Views: 2207

Answers (3)

see sharper
see sharper

Reputation: 12035

Given this is node, and not React as the original tag suggested, it could be as easy as:

const axios = require("axios");
var posts;
await (async () => {
  const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
  posts = allPosts;
})();
// do something with posts

Upvotes: 0

Clark
Clark

Reputation: 305

You can consider use callback function, like below code snippet:

const axios = require("axios");

(async () => {
  const allPosts = await axios.get("http://jsonplaceholder.typicode.com/posts");
  someThingYouWantToDo(allPosts);
})()

const someThingYouWantToDo = (posts) => {
  console.log(posts);
};

Upvotes: 1

see sharper
see sharper

Reputation: 12035

Usually you would assign posts to a state variable inside the async function right after receiving the data, and that would trigger a re-render. Or you would call a redux dispatch action to set the value in redux and redux would update the props. So in short, it's the usual React way: update state or props to render the view, use componentDidUpdate for any additional logic. For example:

const axios = require("axios");
var posts;
(async () => {
  const allPosts = await 
  axios.get("http://jsonplaceholder.typicode.com/posts");
  posts = allPosts;
  this.setState({
    posts,
  })
})()

Upvotes: 1

Related Questions