1

I'm able to use fetch api (wanted to do the fetch api rather than axios) and call out my local api and console.log the data from my api.js file -

 export default {
     async getData(){
         await fetch(url+"campground")
        .then(result => result.json())
        .then(data => {
            console.log(data) // [{id:123,name:"Shimla"},{id:124,name:"Manali"}]
            return data
        })
    }
 }

The issue arises when I try to do it on my Catalogue.vue file.

<script>
      import api from '../api';
      export default {
        name: 'Catalogue',
        data() {
          return {
            camps: null
          }
        },
        methods: {
          
        },
        created() {
           this.camps = api.getData() 
           console.log(this.camps) //Promise { <state>: "pending" }
        },
      }
    
    </script>

The result that I get is usually

Promise { : "pending" }

How can I proceed from here? Thank You

1 Answer 1

2

You're not returning anything from getData and because fetch is async you don't need to put async/await on it.

Change to

export default {
    getData(){
        return fetch(url+"campground")
        .then(result => result.json())
    }
}

Then because its return value is a promise, you need to await it (as others have said)

async created() {
  try {
    this.camps = await api.getData() 
  } catch {
    this.camps = []
  }
},

or

created() {
  api.getData().then(result => this.camps = result).catch(e => this.camps = [])
},

btw, if camps ends up as an array from the result you should define it as an empty array in data not null.

Sign up to request clarification or add additional context in comments.

3 Comments

I'll ignore url not being defined
Thank you. Your solution worked! I need to return the fetch like you said.
np, glad it helped

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.