0

I want to make an API call from which the component's data gets initialized:

<script>
  export default {
    data() {
        const fetchURL = `http://127.0.0.1:8000/data`;
        response = await fetch(fetchURL)
        return await response.json()
    }
  }
</script>

This approach doesn't work because data() can't be async. What's the right idiom to use here?

1 Answer 1

2

You could initialize an empty array called items inside the data option and use the created hook to update it :


<script>
  export default {
    data() {
     return{
       items:[]
     }
    },
   async created(){
       const fetchURL = `http://127.0.0.1:8000/data`;
        response = await fetch(fetchURL)
        this.items= await response.json()
    }
  }
</script>


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

Comments

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.