0
votes

I learn how to use new composition api in Vue 3 and in one lesson I see how can be use calls to api with composition api but I can't make it work with my code. I'm making call api in const getPosts = usePromise(PostService.getAll()); - the api call to the server is successful but I can't load posts in components. In console.log(getPosts) - enter image description here view/PostList.vue

<template>
  <div>
    <Loader v-if="getPosts.loading" />
    <div v-for="post in posts" :key="post.id"></div>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue';
import { Post } from '../types';
import PostService from '../services/PostService';
import usePromise from '../composables/use-promise';
import Loader from '../components/ui/Loader.vue';

export default {
  components: { Loader },
  setup() {
    const posts = ref<Post[]>([]);
    const post = ref<Post>({
      title: '',
      body: '',
    });
    const getPosts = usePromise(PostService.getAll());
    console.log(getPosts);
    posts.value = getPosts.result.value;

    return { posts, post, getPosts };
  },
};
</script>

composables/use-promise.ts - console.log(response) - Response is never seen in console

import { ref } from 'vue';
export default function usePromise(fn: any) {
  // fn is the actual API call
  const result = ref(null);
  const loading = ref(false);
  const error = ref(null);
  const createPromise = async (...args: any) => {
    // Args is where we send in searchInput
    loading.value = true;
    error.value = null;
    result.value = null;
    try {
      const response = await fn(...args);
      console.log(response);
      result.value = response;
    } catch (err) {
      error.value = err;
    } finally {
      loading.value = false;
    }
  };

  return { result, loading, error, createPromise };
}

services/Api.ts

import axios from 'axios';

export default axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com/',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  },
});

services/PostService.ts

import Api from './Api';
export default {
  async getAll() {
    const response = await Api.get('/posts');
    return response.data;;
  },
};
1

1 Answers

0
votes

You need to use your promise hook as below:

const posts = ref < Post[] > ([]);
const {
  createPromise,
  result
} = usePromise(PostService.getAll);

createPromise().then(() => {
  console.log(result.value.data);
  posts.value = result.value.data as Post[]
})