Skip to content

RJS-2648: Add ability for Realm instance to be used in RealmProvider #6714

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

Merged
merged 32 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
58ae94e
update 5 files
gagik Jun 10, 2024
3347509
Merge branch 'main' of github.com:realm/realm-js into gagik/realm-ins…
gagik Jun 10, 2024
776b6c5
renames in RealmProvider.tsx, RealmProvider.test.tsx and packages/rea…
gagik Jun 11, 2024
d2799d2
update RealmContext.ts, RealmProvider.tsx, RealmProvider.test.tsx and…
gagik Jun 11, 2024
5e419b5
update RealmProvider.tsx and RealmProvider.test.tsx
gagik Jun 11, 2024
58222e0
test: update RealmProvider.test.tsx
gagik Jun 12, 2024
7756a56
docs: update CHANGELOG.md
gagik Jun 12, 2024
bf99a62
update CHANGELOG.md and RealmProvider.tsx
gagik Jun 12, 2024
9788883
Merge branch 'main' of github.com:realm/realm-js into gagik/realm-ins…
gagik Jun 12, 2024
88c9790
update RealmContext.ts and RealmProvider.tsx
gagik Jun 12, 2024
eabe2bd
rename flexible provider to generalized
gagik Jun 13, 2024
f454eae
changes based on review
gagik Jun 14, 2024
9fde880
Update from review comments
gagik Jun 14, 2024
73bff55
Update CHANGELOG.md
gagik Jun 17, 2024
282f71a
PR changes
gagik Jun 17, 2024
bf4797a
Merge branch 'gagik/realm-instance-provider' of github.com:realm/real…
gagik Jun 17, 2024
9f0366c
Reorganize and cleanup
gagik Jun 17, 2024
af1f579
update CHANGELOG.md and RealmProvider.tsx
gagik Jun 17, 2024
f024e9b
update RealmContext.ts, RealmProvider.tsx and packages/realm-react/sr…
gagik Jun 17, 2024
91d28b3
Fix comment
gagik Jun 17, 2024
bb938f7
update packages/realm-react/src/index.tsx
gagik Jun 17, 2024
39e486b
Merge branch 'main' of github.com:realm/realm-js into gagik/realm-ins…
gagik Jun 17, 2024
0b7c9c8
Fix html
gagik Jun 17, 2024
dd0ab56
Merge branch 'main' of github.com:realm/realm-js into gagik/realm-ins…
gagik Jun 17, 2024
dda07c9
Add semicolon
gagik Jun 17, 2024
aff7d8a
Add errors with props
gagik Jun 17, 2024
e1b71e1
use less unrolling
gagik Jun 17, 2024
e5fc4c8
rename to configprops
gagik Jun 17, 2024
faeec83
update RealmProvider.tsx
gagik Jun 17, 2024
8639d84
Update packages/realm-react/CHANGELOG.md
gagik Jun 17, 2024
436ff07
More than 0
gagik Jun 17, 2024
c34b4a1
Merge branch 'gagik/realm-instance-provider' of github.com:realm/real…
gagik Jun 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,29 @@
### Enhancements
* Report the originating error that caused a client reset to occur. ([realm/realm-core#6154](https://github.com/realm/realm-core/issues/6154))
* Reduce the size of the local transaction log produced by creating objects, improving the performance of insertion-heavy transactions. ([realm/realm-core#7734](https://github.com/realm/realm-core/pull/7734))
* Added the ability to use an existing Realm instance in `RealmProvider` and `createRealmContext`. ([#6714](https://github.com/realm/realm-js/pull/6714))
```jsx
// Using RealmProvider
import { RealmProvider } from "@realm/react";
...
const realm = new Realm(...);
...
return <RealmProvider realm={realm}>
...
</RealmProvider>

// Using createRealmContext
import { createRealmContext } from "@realm/react";
...
const realm = new Realm(...);

const { RealmProvider, useRealm } = createRealmContext(realm);
...
return <RealmProvider>
...
</RealmProvider>
```


### Fixed
* After compacting, a file upgrade would be triggered. This could cause loss of data for synced Realms. ([realm/realm-core#7747](https://github.com/realm/realm-core/issues/7747), since 12.7.0-rc.0)
Expand Down
109 changes: 109 additions & 0 deletions packages/realm-react/src/RealmContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2024 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////

import { createUseObject } from "./useObject";
import { createUseQuery } from "./useQuery";
import { createUseRealm } from "./useRealm";
import { GeneralizedRealmProviderFC } from "./RealmProvider";

export type RealmContext<RealmProvider = GeneralizedRealmProviderFC> = {
/**
* The Provider component that is required to wrap any component using
* the Realm hooks.
* @example
* ```
* const AppRoot = () => {
* const syncConfig = {
* flexible: true,
* user: currentUser
* };
*
* return (
* <RealmProvider schema={[Task, User]} path={"data.realm"} sync={syncConfig}>
* <App/>
* </RealmProvider>
* )
* }
* ```
* @param props - The {@link Realm.Configuration} or {@link Realm} of the provider
* are set based on the options passed to `createRealmProvider`. When using a
* {@link Realm.Configuration}, individual config keys can be overridden when
* creating a `<RealmProvider>` by passing them as props. For example, to override
* the `path` config value, use a prop named `path` e.g., `path="newPath.realm"` an
* attribute of the same key.
*/
RealmProvider: RealmProvider;
/**
* Returns the instance of the {@link Realm} opened by the `RealmProvider`.
* @example
* ```
* const realm = useRealm();
* ```
* @returns a realm instance
*/
useRealm: ReturnType<typeof createUseRealm>;

/**
* Returns a {@link Realm.Collection} of {@link Realm.Object}s from a given type.
* The hook will update on any changes to any object in the collection
* and return an empty array if the collection is empty.
*
* The result of this can be consumed directly by the `data` argument of any React Native
* VirtualizedList or FlatList. If the component used for the list's `renderItem` prop is {@link React.Memo}ized,
* then only the modified object will re-render.
* @example
* ```tsx
* // Return all collection items
* const collection = useQuery({ type: Object });
*
* // Return all collection items sorted by name and filtered by category
* const filteredAndSorted = useQuery({
* type: Object,
* query: (collection) => collection.filtered('category == $0',category).sorted('name'),
* }, [category]);
*
* // Return all collection items sorted by name and filtered by category, triggering re-renders only if "name" changes
* const filteredAndSorted = useQuery({
* type: Object,
* query: (collection) => collection.filtered('category == $0',category).sorted('name'),
* keyPaths: ["name"]
* }, [category]);
* ```
* @param options
* @param options.type - The object type, depicted by a string or a class extending Realm.Object
* @param options.query - A function that takes a {@link Realm.Collection} and returns a {@link Realm.Collection} of the same type. This allows for filtering and sorting of the collection, before it is returned.
* @param options.keyPaths - Indicates a lower bound on the changes relevant for the hook. This is a lower bound, since if multiple hooks add listeners (each with their own `keyPaths`) the union of these key-paths will determine the changes that are considered relevant for all listeners registered on the collection. In other words: A listener might fire and cause a re-render more than the key-paths specify, if other listeners with different key-paths are present.
* @param deps - An array of dependencies that will be passed to {@link React.useMemo}
* @returns a collection of realm objects or an empty array
*/
useQuery: ReturnType<typeof createUseQuery>;
/**
* Returns a {@link Realm.Object} from a given type and value of primary key.
* The hook will update on any changes to the properties on the returned object
* and return null if it either doesn't exists or has been deleted.
* @example
* ```
* const object = useObject(ObjectClass, objectId);
* ```
* @param type - The object type, depicted by a string or a class extending {@link Realm.Object}
* @param primaryKey - The primary key of the desired object which will be retrieved using {@link Realm.objectForPrimaryKey}
* @param keyPaths - Indicates a lower bound on the changes relevant for the hook. This is a lower bound, since if multiple hooks add listeners (each with their own `keyPaths`) the union of these key-paths will determine the changes that are considered relevant for all listeners registered on the object. In other words: A listener might fire and cause a re-render more than the key-paths specify, if other listeners with different key-paths are present.
* @returns either the desired {@link Realm.Object} or `null` in the case of it being deleted or not existing.
*/
useObject: ReturnType<typeof createUseObject>;
};
131 changes: 100 additions & 31 deletions packages/realm-react/src/RealmProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//
////////////////////////////////////////////////////////////////////////////

import React, { useContext, useEffect, useRef, useState } from "react";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import Realm from "realm";
import { isEqual } from "lodash";

Expand All @@ -26,11 +26,11 @@ type PartialRealmConfiguration = Omit<Partial<Realm.Configuration>, "sync"> & {
sync?: Partial<Realm.SyncConfiguration>;
};

type ProviderProps = PartialRealmConfiguration & {
type RealmProviderProps = {
/**
* The fallback component to render if the Realm is not opened.
* The Realm instance to be used by the provider.
*/
fallback?: React.ComponentType<unknown> | React.ReactElement | null | undefined;
realm?: Realm;
/**
* If false, Realm will not be closed when the component unmounts.
* @default true
Expand All @@ -41,43 +41,73 @@ type ProviderProps = PartialRealmConfiguration & {
* instance outside of a component that uses the Realm hooks.
*/
realmRef?: React.MutableRefObject<Realm | null>;
/**
* The fallback component to render if the Realm is not open.
*/
fallback?: React.ComponentType<unknown> | React.ReactElement | null | undefined;
children: React.ReactNode;
};
} & PartialRealmConfiguration;

/**
Represents the provider returned from using an existing realm at context creation i.e. `createRealmContext(new Realm))`.
*/
export type RealmProviderFromRealmInstanceFC = React.FC<Pick<RealmProviderProps, "children">>;

/**
* Represents the provider returned from using a Realm configuration at context creation i.e. `createRealmContext({schema: []}))`.
*/
export type RealmProviderFromConfigFC = React.FC<
Pick<RealmProviderProps, "closeOnUnmount" | "realmRef" | "fallback" | "children" | keyof PartialRealmConfiguration>
>;

/**
* Explicitly sets the unpicked properties of a type to never instead of dropping them like in Pick.
* Useful for ensuring different prop types are mutually exclusive as React expects the union type
* of different prop types to include all the fields.
*/
type RestrictivePick<T, K extends keyof T> = Pick<T, K> & { [RestrictedKey in keyof Omit<T, K>]?: never };

/**
* Represents properties of a generic RealmProvider where the realm is set and therefore all other
* props should be disallowed.
*/
export type RealmProviderWithRealmInstanceProps = RestrictivePick<RealmProviderProps, "realm" | "children">;

/*
* Represents properties of a generic RealmProvider where Realm configuration props are used and no realm is set
*/
export type RealmProviderWithConfigurationProps = RestrictivePick<
RealmProviderProps,
"closeOnUnmount" | "realmRef" | "fallback" | "children" | keyof PartialRealmConfiguration
>;

/**
* Represents the provider returned from creating context with no arguments (including the default context).
* Supports either passing a `realm` as a property or the schema configuration.
*/
export type GeneralizedRealmProviderFC = React.FC<
RealmProviderWithRealmInstanceProps | RealmProviderWithConfigurationProps
>;

export function createRealmProviderFromRealm(
realm: Realm | null,
RealmContext: React.Context<Realm | null>,
): RealmProviderFromRealmInstanceFC {
return ({ children }) => {
return <RealmContext.Provider value={realm} children={children} />;
};
}

/**
* Generates a `RealmProvider` given a {@link Realm.Configuration} and {@link React.Context}.
* @param realmConfig - The configuration of the Realm to be instantiated
* @param RealmContext - The context that will contain the Realm instance
* @returns a RealmProvider component that provides context to all context hooks
*/
export function createRealmProvider(
export function createRealmProviderFromConfig(
realmConfig: Realm.Configuration,
RealmContext: React.Context<Realm | null>,
): React.FC<ProviderProps> {
/**
* Returns a Context Provider component that is required to wrap any component using
* the Realm hooks.
* @example
* ```
* const AppRoot = () => {
* const syncConfig = {
* flexible: true,
* user: currentUser
* };
*
* return (
* <RealmProvider path="data.realm" sync={syncConfig}>
* <App/>
* </RealmProvider>
* )
* }
* ```
* @param props - The {@link Realm.Configuration} for this Realm defaults to
* the config passed to `createRealmProvider`, but individual config keys can
* be overridden when creating a `<RealmProvider>` by passing them as props.
* For example, to override the `path` config value, use a prop named `path`,
* e.g. `path="newPath.realm"`
*/
): RealmProviderFromConfigFC {
return ({ children, fallback: Fallback, closeOnUnmount = true, realmRef, ...restProps }) => {
const [realm, setRealm] = useState<Realm | null>(() =>
realmConfig.sync === undefined && restProps.sync === undefined
Expand Down Expand Up @@ -161,6 +191,45 @@ export function createRealmProvider(
};
}

/**
* Generates a flexible `RealmProvider` which is either based on a configuration
* or based on a realm, depending on its props.
* @param RealmContext - The context that will contain the Realm instance
* @returns a RealmProvider component that provides context to all context hooks
*/
export function createGeneralizedRealmProvider(RealmContext: React.Context<Realm | null>): GeneralizedRealmProviderFC {
return ({ realm, ...restProps }) => {
return useMemo(() => {
if (realm != null) {
const RealmProviderFromRealm = createRealmProviderFromRealm(realm, RealmContext);
return <RealmProviderFromRealm {...restProps} />;
} else {
const RealmProviderFromConfig = createRealmProviderFromConfig({}, RealmContext);
return <RealmProviderFromConfig {...restProps} />;
}
}, [realm]);
};
}

/**
* Generates the appropriate `RealmProvider` based on whether there is a config, realm, or neither given.
* @param realmOrRealmConfig - An existing Realm, a configuration, or undefined (including default provider).
* @param RealmContext - The context that will contain the Realm instance
* @returns a RealmProvider component that provides context to all context hooks
*/
export function createRealmProvider(
realmOrRealmConfig: Realm.Configuration | Realm | undefined,
RealmContext: React.Context<Realm | null>,
): RealmProviderFromConfigFC | RealmProviderFromRealmInstanceFC | GeneralizedRealmProviderFC {
if (realmOrRealmConfig == undefined) {
return createGeneralizedRealmProvider(RealmContext);
} else if (realmOrRealmConfig instanceof Realm) {
return createRealmProviderFromRealm(realmOrRealmConfig, RealmContext);
} else {
return createRealmProviderFromConfig(realmOrRealmConfig, RealmContext);
}
}

/**
* Merge two configurations, creating a configuration using `configA` as the default,
* merged with `configB`, with properties in `configB` overriding `configA`.
Expand Down
Loading
Loading