-2

When I access https://jsonplaceholder.typicode.com/todos?_limit=1 in my browser I get:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
]

I am now trying store the result (and print) of a simple http GET request in a variable using axios in vue.js with the above URL:

  const result = axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
  console.log("result is = " + result)
  console.log("result.title is = " + result.title)

But the above gives the below output:

App.vue?234e:59 result is = [object Promise]
App.vue?234e:60 result.title is = undefined

Is it not possible to print a json friendly result from a http get request (like with curl) without having to deal with promisesin vue.js?

UPDATE:

Based on below answers I have now tried the following in my App.vue file

<script>

import axios from 'axios';

export default {
  name: 'app',
  components: {
    AddTodo
  },
  data(){
    return {
      todos: []
    }
  },

  methods: {
    // not allowed to use function keyword here  
    async printJson(){
      let result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
      console.log("result is = " + result)
      console.log("result.title is = " + result.title)
    },    

    addTodo(newTodo) {
      this.printJson()  
    }
  }
}
</script>

But that just gives:

App.vue?234e:50 result is = [object Object]
App.vue?234e:51 result.title is = undefined
u123
  • 15,603
  • 58
  • 186
  • 303
  • If you want to avoid chaining promises to keep a beautiful and readable code. You can take a look at async/await on JS. Even while doing requests directly with JS API, you will have to use callbacks or promises. It is asynchronous – Martin Paucot Feb 05 '20 at 15:56

4 Answers4

1

Well thats not the way to do it...

Here are few ways to do it:

(async function(){
   const result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
   console.log("result is = " + result.data)
   console.log("result.title is = " + result.data.title)
})()

or the old way like this:

axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1').then(function(result){
console.log("result is = " + result.data)
console.log("result.title is = " + result.data.title)
})
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Ok but what if I want to store the result in a variable and print the content after the axios get call? – u123 Feb 05 '20 at 17:14
  • first you declare an variable for example `var myData;` and then you can set your result data to your `myData` like this: `myData = result.data`, now is your result stored in your variable. but be sure if you call the variable that you already fetched the data – bill.gates Feb 05 '20 at 17:23
  • Not sure what you mean can you provide a full example? – u123 Feb 06 '20 at 07:55
  • You already store the result in a variable called "result". Maybe you should first explain what you want to do. – Xellos Feb 06 '20 at 08:20
  • I want the variable to be available outside the async or promise scope. But looks like that is not possible. – u123 Feb 06 '20 at 11:38
1

Yeah most of us do not want to deal with promises. Which is why the new JavaScript added async and await keywords.

function call(){
  return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}

async function printJson(){
  let result = await call();
  console.log("result is = " + result)
  console.log("result.title is = " + result.title)
}

I pulled your call in a separate function to highlight the await better. I think it is not required (but cleaner in either case).

Technically there is still the promise, but you do not deal with it; Javascript does now. There is also a ton of information out there about async and await. As you can imagine, a lot of people want to get away from infinitely stacked callbacks.

UPDATE

I have run this through a fiddle now myself and the code works, once the access is adjusted to the structure of the returning JSON, which is an array of objects.

See this fiddle https://jsfiddle.net/xb2fck19/1/

Also you can put functions in the vue methods like this


<script>

import axios from 'axios';

//Version 1 - private function
function call(){
  return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
}

export default {
  name: 'app',
  components: {
    AddTodo
  },
  data(){
    return {
      todos: []
    }
  },

  methods: {
    // not allowed to use function keyword here  
    async printJson(){
      //make this.call(); if using version 2
      let result = await call();
      let data = result.data;
      console.log(data);
      for (let entry of data){
        console.log("result is = " + entry)
        console.log("result.title is = " + entry.title)
      }
    },   
    //Version 2 - public function
    call(){
      return axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
    }
    addTodo(newTodo) {
      this.printJson()  
    }
  }
}
</script>

Xellos
  • 87
  • 1
  • 7
  • That does not work, see my updated post - also the keyword 'function' is not allowed in the methods scope. – u123 Feb 06 '20 at 08:20
  • It has been a while since I used axios. Your println says it is Object object now. Can you check if it has a data property below? Might just have to do result.data and result.data.title – Xellos Feb 06 '20 at 08:52
  • It does work, if you adjust the code to your JSON structure, which you failed to mention. If you do not tell us that you have an array of objects, of course result.data.title is undefined. Hence I asked you to check the properties... – Xellos Feb 06 '20 at 14:38
  • In my original post you can see the full json blop I am trying to access. Using you example it works but it will require that I specify each "field" explicitly. I had hoped it was possible to just output the full blop like with curl but seems that not how axios is designed. +1 for also showing valid function keyword outside export scope. – u123 Feb 09 '20 at 09:40
0

Axios returns Promise always so you can use then()

axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1').then(response => { console.log(response); }

Ajay Kumar
  • 99
  • 6
  • But I want to store the result in a variable that I may or may not print to console after its as been assigned the response result – u123 Feb 06 '20 at 07:55
0

Found the answer based on:

Show json result with vue.js

actually very simply I just need to use JSON.stringify(data):

async printJson(){
  let result = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=1');
  let data = result.data
  let pretty =   JSON.stringify(data)
  console.log("Pretty = " + pretty)
},    

which gives:

App.vue?234e:54 Pretty = [{"userId":1,"id":1,"title":"delectus aut autem","completed":false}]
u123
  • 15,603
  • 58
  • 186
  • 303