Using JSData in the Browser

How-To Guides

Using JSData in the Browser

JSData works in Node.js and in the browser, opening up the possibility of universal models (model code is shared between the client and the server). Currently available client-side adapters: HTTP, Firebase, and LocalStorage.

Check out our example application which shows how to use JSData with shared code between the browser and Node.js.

The browser is quite a different environment than the server with different performance and data handling considerations.

👍

Tip

In the browser you should use the SimpleStore or DataStore components to leverage the in-memory data store, but it's okay to start out with just the Container component` before moving on to the in-memory store.

Why use SimpleStore or DataStore instead of Container? Container is just a way to manage your Mappers, and does not provide any in-memory caching functionality. If you're building a single-page app, then it's likely you want to cache data as users navigate between different views of your app.

👍

Tip

When using JSData in the browser, take care to understand the difference between find() and findAll(). Note also the difference between loading data from your server into the store and reading data from the store for use in your app's Views.

See Understanding find() vs findAll()

Example

Here's an example of setting JSData up in the browser:

import { DataStore } from 'js-data';
import { HttpAdapter } from 'js-data-http';

const adapter = new HttpAdapter({
  basePath: 'api'
});

const store = new DataStore();
store.registerAdapter('http', adapter, { default: true });

store.defineMapper('post', {
  endpoint: 'posts'
});

// GET /api/posts
store.findAll('post', { published: true })
  .then((posts) => {
    // Received an array of posts from the server
    console.log(posts);

    // Those same post records are now cached in the store as well
    console.log(store.filter('post', { published: true }));
  });

Using JSData in different bundlers

JSData uses the UMD (Universal Module Definition) pattern in order to work with different module systems and bundlers. Here are some examples of loading JSData and the HTTP adapter with various bundlers: