DEV Community

Manuel Ojeda
Manuel Ojeda

Posted on

How to use Vue Composition API using TypeScript - Part 2

As we saw in the previous post, we started a project to make use of the Vue Composition API and TypeScript, in case you didn't read the post, you can check it out here:
https://dev.to/manuelojeda/how-to-use-vue-composition-api-using-typescript-part-1-5a00

So, without anything else to say!

Alt Text

Previewing and preparing the project directory

As you may know by now, the Vue CLI make a base setup of the project, but before the start we need to add some folders into the project, we are adding two folders into the src directory: interfaces and services, once we added those two folders our directory wil be set like this:

Alt Text

Building the interface and the service

As you may know, TypeScript give us the opportunity to add Interfaces and Services into a project (of course the main use is adding the type enforcement), before we start we need to set a background of what is both of those terms:

  • Interfaces are the contract that will follow one or more variables, and will only accept certains values added into the interface
  • Services are what normally we use as an API, giving us all the function we may need to consume/use.

Now let's create some code!

Character.ts

Inside the interfaces directory create a file named "Character.ts" and we add the next code:

interface Character {
  name?: string;
  height?: string;
  mass?: string;
  hair_color?: string;
  skin_color?: string;
  eye_color?: string;
  birth_year?: string;
  gender?: string;
  homeworld?: string;
  films?: string[];
  species?: string[];
  vehicles?: string[];
  starships?: string[];
  url?: string;
}

export default Character

Note: As you notice, I added a ? besides the variable name just to avoid any warning when we initialize an empty variable using this contract.

After we have settle our contract, we may proceed to create our service.

CharacterService.ts

Inside the services directory add the following file "CharacterService.ts", we are just creating a singleton class that will only get the data (our heroes and villains) we may need in our Vue components.

import axios from 'axios'
import Character from '@/interfaces/Character'

class CharacterService {
  async FetchCharacters (): Promise<Character[] | any[]> {
    let response: Character[] | any[] = []
    try {
      const { data, status } = await axios({
        url: 'https://swapi.co/api/people/'
      })

      if (data && status === 200) {
        response = data.results
      }
      return response
    } catch (error) {
      response = [
        {
          error: error.response as object,
          flag: false as boolean,
          generalError: 'An error happened' as string
        }
      ]
      return response
    }
  }
}

export default CharacterService

As you may noticed we prepared our function as await/async to make our code cleaner and added an alternative response type in case and error occurs while we are fetching out information.

For now on we have prepared the interface and service code, in the next and last part we are going to set our Vue app and connect in all together to make this app working.

Top comments (4)

Collapse
 
peterkassenaar profile image
Peter Kassenaar

Hi Manuel,

Thanks for the articles.

Since axios unwraps the reponse by default, I think it is not necessary to write response = data.results. You should be able to use just response = data?

Or am I missing something here?

Collapse
 
victoravelar profile image
Victor Avelar

Just a recommendation, you can create series in dev.to, that way you don't need to paste the full URL to the previous article, this will make easier to read all the posts for the same topic.

Collapse
 
manuelojeda profile image
Manuel Ojeda

Oh thanks Victor, these were my first 3 post in the website

Collapse
 
victoravelar profile image
Victor Avelar

I've seen that, keep it going and welcome to the community.

p.s. Viva México 😄