tldraw/apps/dotcom/src/hooks/useLocalStore.ts
Steve Ruiz d7002057d7
unbrivate, dot com in (#2475)
This PR moves the tldraw.com app into the public repo.

### Change Type

- [x] `internal` — Any other changes that don't affect the published
package[^2]

---------

Co-authored-by: Dan Groshev <git@dgroshev.com>
Co-authored-by: alex <alex@dytry.ch>
2024-01-16 14:38:05 +00:00

34 lines
1 KiB
TypeScript

import {
MigrationFailureReason,
Result,
SerializedSchema,
TLRecord,
TLStore,
createTLStore,
} from '@tldraw/tldraw'
import { schema } from '@tldraw/tlsync'
import { useEffect, useState } from 'react'
export function useLocalStore(records: TLRecord[], serializedSchema: SerializedSchema) {
const [storeResult, setStoreResult] = useState<
Result<TLStore, MigrationFailureReason> | undefined
>(undefined)
useEffect(() => {
const store = createTLStore({ schema })
const snapshot = Object.fromEntries(records.map((r) => [r.id, r]))
const migrationResult = store.schema.migrateStoreSnapshot({
store: snapshot,
schema: serializedSchema,
})
if (migrationResult.type === 'error') {
setStoreResult(Result.err(migrationResult.reason))
console.error('failed to migrate store', migrationResult)
} else {
store.mergeRemoteChanges(() => {
store.put(Object.values(migrationResult.value), 'initialize')
})
setStoreResult(Result.ok(store))
}
}, [records, serializedSchema])
return storeResult
}