0

I used vue 2 quiet a lot and now finally trying to slowly using vue 3 but I am already kind of buffled of how this works. In vue 2, I used the created method to fetch API data and populate my data arrays. Now I was trying the vue 3 way by using onMounted and I can log the API response. What I dont seem to find out is, how can I make my streams array to be initialized by the json response from the API now?

<script setup lang="ts">
import { ref, onMounted } from "vue";
let streams = ref(); //should be array of Objects {marketId, timeframe}
onMounted(() => {
  fetch("http://localhost:3000/stream")
    .then((response) => response.json())
    .then((result) => (streams.value = result)); //json response array  {marketId, timeframe}, {marketId, timeframe}
  console.log(streams.value); //returns undefined
});
</script>

1 Answer 1

1

Try to wait for response:

const { ref, onMounted } = Vue
const app = Vue.createApp({
  setup() {
    let streams = ref();
    onMounted(async () => {
      await fetch("https://jsonplaceholder.typicode.com/users")
        .then((response) => response.json())
        .then((result) => (streams.value = result)); 
    });
    return {
      streams,
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="stream in streams">
    {{ stream }}
  </div>
</div>

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.