Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add data sharing across tabs in ra-data-local-storage #8542

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 36 additions & 5 deletions packages/ra-data-localstorage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A dataProvider for [react-admin](https://github.com/marmelab/react-admin) that uses a local database, persisted in localStorage.

The provider issues no HTTP requests, every operation happens locally in the browser. User editions are persisted across refreshes and between sessions. This allows local-first apps, and can be useful in tests.
The provider issues no HTTP requests; every CRUD query happens locally in the browser. User editions are shared between tabs, and persisted even after a user session ends. This allows local-first apps, and can be useful in tests.

## Installation

Expand All @@ -12,6 +12,10 @@ npm install --save ra-data-local-storage

## Usage

The default export is a function that returns a data provider.

When used without parameters, the data provider uses a local database with no data. You can then use the `useDataProvider` hook to populate it. The changes are persisted in localStorage (in the `ra-data-local-storage` key), so they will be available on the next page load.

```jsx
// in src/App.js
import * as React from "react";
Expand All @@ -30,11 +34,18 @@ const App = () => (
export default App;
```

### defaultData
The function accepts an options object as parameter, with the following keys:

- `defaultData`: an object literal with one key for each resource type, and an array of resources as value. See below for more details.
- `loggingEnabled`: a boolean to enable logging of all calls to the data provider in the console. Defaults to `false`.
- `localStorageKey`: the key to use in localStorage to store the data. Defaults to `ra-data-local-storage`.
- `localStorageUpdateDelay`: the delay (in milliseconds) between a change in the data and the update of localStorage. Defaults to 10 milliseconds.

## `defaultData`

By default, the data provider starts with no resource. To set default data if the storage is empty, pass a JSON object as the `defaultData` argument:

```js
```jsx
const dataProvider = localStorageDataProvider({
defaultData: {
posts: [
Expand All @@ -53,16 +64,36 @@ The `defaultData` parameter must be an object literal with one key for each reso

Foreign keys are also supported: just name the field `{related_resource_name}_id` and give an existing value.

### loggingEnabled
## `loggingEnabled`

As this data provider doesn't use the network, you can't debug it using the network tab of your browser developer tools. However, it can log all calls (input and output) in the console, provided you set the `loggingEnabled` parameter:

```js
```jsx
const dataProvider = localStorageDataProvider({
loggingEnabled: true
});
```

## `localStorageKey`

By default, the data provider uses the `ra-data-local-storage` key in localStorage. You can change this key by passing a `localStorageKey` parameter:

```jsx
const dataProvider = localStorageDataProvider({
localStorageKey: 'my-app-data'
});
```

## `localStorageUpdateDelay`

By default, the data provider updates localStorage 10 milliseconds after every change. This can be slow if you have a lot of data. You can change this behavior by passing a `localStorageUpdateDelay` parameter:

```jsx
const dataProvider = localStorageDataProvider({
localStorageUpdateDelay: 2
});
```

## Features

This data provider uses [FakeRest](https://github.com/marmelab/FakeRest) under the hood. That means that it offers the same features:
Expand Down
25 changes: 18 additions & 7 deletions packages/ra-data-localstorage/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import pullAt from 'lodash/pullAt';
/**
* Respond to react-admin data queries using a local database persisted in localStorage
*
* Useful for local-first web apps.
* Useful for local-first web apps. The storage is shared between tabs.
*
* @example // initialize with no data
*
Expand Down Expand Up @@ -37,7 +37,7 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
localStorageUpdateDelay = 10, // milliseconds
} = params || {};
const localStorageData = localStorage.getItem(localStorageKey);
const data = localStorageData ? JSON.parse(localStorageData) : defaultData;
let data = localStorageData ? JSON.parse(localStorageData) : defaultData;

// change data by executing callback, then persist in localStorage
const updateLocalStorage = callback => {
Expand All @@ -48,11 +48,22 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
}, localStorageUpdateDelay);
};

const baseDataProvider = fakeRestProvider(
let baseDataProvider = fakeRestProvider(
data,
loggingEnabled
) as DataProvider;

window?.addEventListener('storage', event => {
if (event.key === localStorageKey) {
const newData = JSON.parse(event.newValue);
data = newData;
baseDataProvider = fakeRestProvider(
newData,
loggingEnabled
) as DataProvider;
}
});

return {
// read methods are just proxies to FakeRest
getList: <RecordType extends RaRecord = any>(resource, params) =>
Expand Down Expand Up @@ -88,7 +99,7 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
// update methods need to persist changes in localStorage
update: <RecordType extends RaRecord = any>(resource, params) => {
updateLocalStorage(() => {
const index = data[resource].findIndex(
const index = data[resource]?.findIndex(
record => record.id == params.id
);
data[resource][index] = {
Expand All @@ -101,7 +112,7 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
updateMany: (resource, params) => {
updateLocalStorage(() => {
params.ids.forEach(id => {
const index = data[resource].findIndex(
const index = data[resource]?.findIndex(
record => record.id == id
);
data[resource][index] = {
Expand All @@ -128,7 +139,7 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
},
delete: <RecordType extends RaRecord = any>(resource, params) => {
updateLocalStorage(() => {
const index = data[resource].findIndex(
const index = data[resource]?.findIndex(
record => record.id == params.id
);
pullAt(data[resource], [index]);
Expand All @@ -138,7 +149,7 @@ export default (params?: LocalStorageDataProviderParams): DataProvider => {
deleteMany: (resource, params) => {
updateLocalStorage(() => {
const indexes = params.ids.map(id =>
data[resource].findIndex(record => record.id == id)
data[resource]?.findIndex(record => record.id == id)
);
pullAt(data[resource], indexes);
});
Expand Down