Skip to content

Latest commit

 

History

History
105 lines (72 loc) · 2.62 KB

quick-start.md

File metadata and controls

105 lines (72 loc) · 2.62 KB

Quick start

Home > Quick Start

Intro

To use Axios Actions you need to do four things:

Note: the examples on this page are written as if each chunk of functionality is imported / exported from separate files

Configure Axios

Because the package's services run on top of an existing Axios setup, you need to provide that first:

// axios.js
import axios from 'axios'

// create instance
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
});

// optional auth, interceptors, etc
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.interceptors.request.use( ... )
instance.interceptors.response.use( ... )

// export new instance
export default instance

This needs only to be done once, and will used throughout your app.

Configure actions

Next, for each set of endpoints, create an actions config which at its most basic is a hash of names and URLs:

// actions.js
const actions = {
  search: 'products/widgets?category=:category',
  update: 'POST products/widgets/:id',
  delete: 'DELETE products/widgets/:id',
}

export default actions

If you have multiple endpoint groups, it might be easier to create separate files for each.

Set up a service

Once everything is set up, import everything you need and instantiate the service – in this case ApiGroup:

// widgets.js
import { ApiGroup } from 'axios-actions'
import axios from './axios'
import actions from './actions'

const widgets = new ApiGroup(axios, actions)

At this point you can add additional plugins or add event handlers:

widgets
  .use('data')
  .when('update delete', event => console.log('something changed', event))
  .fail(error => console.log('the request failed', error))

If this is a service you intend to use regularly, you can encapsulate this setup in a single file to be imported as needed:

export default widgets

Use the service

With the service created and configured, it becomes simple to import it, call actions, and handle results:

// main.js
import widgets from './widgets'

widgets
  .search('blue')
  .then(data => {
    console.log(data)
  })

Next steps