Skip to content

Commit

Permalink
Renamed ihp-datasync-react.js to just react.js
Browse files Browse the repository at this point in the history
This makes for nicer es6 imports:

```js
import { useQuery } from 'ihp-datasync/react';
```
  • Loading branch information
mpscholten committed Dec 22, 2021
1 parent a16a6d2 commit 97dd1c1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 40 deletions.
43 changes: 3 additions & 40 deletions lib/IHP/DataSync/ihp-datasync-react.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,3 @@
import React, { useState, useEffect } from 'react';
import { DataSubscription } from './ihp-datasync.js';

// Usage:
//
// const messages = useQuery(query('messages').orderBy('createdAt'));
//
export function useQuery(queryBuilder) {
const [records, setRecords] = useState(null);

useEffect(() => {
const dataSubscription = new DataSubscription(queryBuilder.query);

dataSubscription.onReady = setRecords;
dataSubscription.onUpdate = (id, changeSet) => {
setRecords(records => {
for (const record of records) {
if (record.id === id) {
Object.assign(record, changeSet);
break;
}
}

return [...records];
});
}
dataSubscription.onCreate = newRecord => {
setRecords(records => [...records, newRecord]);
};
dataSubscription.onDelete = id => {
setRecords(records => records.filter(record => record.id !== id));
};

return () => { dataSubscription.close() };
}, [
JSON.stringify(queryBuilder.query) /* <-- It's terrible - but it works, we should find a better for this */
])

return records;
}
/* This file is only kept to avoid breaking b.c. */
import { useQuery } from './react.js';
export { useQuery };
40 changes: 40 additions & 0 deletions lib/IHP/DataSync/react.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React, { useState, useEffect } from 'react';
import { DataSubscription } from './ihp-datasync.js';

// Usage:
//
// const messages = useQuery(query('messages').orderBy('createdAt'));
//
export function useQuery(queryBuilder) {
const [records, setRecords] = useState(null);

useEffect(() => {
const dataSubscription = new DataSubscription(queryBuilder.query);

dataSubscription.onReady = setRecords;
dataSubscription.onUpdate = (id, changeSet) => {
setRecords(records => {
for (const record of records) {
if (record.id === id) {
Object.assign(record, changeSet);
break;
}
}

return [...records];
});
}
dataSubscription.onCreate = newRecord => {
setRecords(records => [...records, newRecord]);
};
dataSubscription.onDelete = id => {
setRecords(records => records.filter(record => record.id !== id));
};

return () => { dataSubscription.close() };
}, [
JSON.stringify(queryBuilder.query) /* <-- It's terrible - but it works, we should find a better for this */
])

return records;
}

0 comments on commit 97dd1c1

Please sign in to comment.