Skip to content
This repository was archived by the owner on Feb 9, 2021. It is now read-only.

Using the network

Darko Kukovec edited this page Jun 29, 2017 · 4 revisions

fetch example

import {config, Store, Record} from 'mobx-jsonapi-store';
config.baseUrl = 'https://example.com/';
const store = new Store();

store.fetch('event', 1) // This will make a GET request to https://example.com/event/1
  .then((response) => {
    const event = response.data;
    console.log(event.id); // 1
  });

fetchAll example

import {config, Store, Record} from 'mobx-jsonapi-store';
config.baseUrl = 'https://example.com/';
const store = new Store();

store.fetchAll('event') // This will make a GET request to https://example.com/event
  .then((response) => {
    const events = response.data;
    console.log(events.length); // e.g. 5
    console.log(events[0].id); // e.g. 1
  });

request example

The request method can be used if something (url, method, etc.) is not standard:

import {config, Store, Record} from 'mobx-jsonapi-store';
config.baseUrl = 'https://example.com/';
const store = new Store();

store.request('event/1/like', 'POST') // This will make a POST request to https://example.com/event/1/like
  .then((response) => {
    // The expected response of the API call is still a valid JSON API response
    const event = response.data;
  });

Pagination example

import {config, Store, Record} from 'mobx-jsonapi-store';

config.baseUrl = 'https://example.com/';
const store = new Store();

// Get a list of all users if the API requires pagination
// Note: In normal usage, you should also have some error handling
async function getAllUsers() {
  const users = [];
  let response = await store.fetchAll('user'); // GET https://example.com/user
  users.push(...response.data);
  while (response.next) {
    response = await response.next;
    users.push(...response.data);
  }
  return users;
}

Clone this wiki locally