Skip to content

Commit c2b045e

Browse files
committed
fix: made firebase context a function to support SSR use cases
1 parent 4554f62 commit c2b045e

File tree

5 files changed

+19
-11
lines changed

5 files changed

+19
-11
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,10 +208,12 @@ data.subscribe(v => doStuff(v) )
208208

209209
### Firebase App Context
210210

211-
The Firebase SDK is available via the [Context API](https://svelte.dev/tutorial/context-api) under the key of `firebase`.
211+
The Firebase SDK is available via the [Context API](https://svelte.dev/tutorial/context-api) under the key of `firebase` using the `getFirebase` function.
212212

213213
```js
214-
const db = getContext('firebase').firestore();
214+
const app = getContext('firebase').getFirebase();
215+
const db = app.firestore();
216+
const auth = app.auth();
215217
```
216218

217219
## API

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"version": "0.1.4",
2+
"version": "0.1.5",
33
"name": "sveltefire",
44
"svelte": "src/index.js",
55
"main": "dist/index.js",

src/FirebaseApp.svelte

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,17 @@
1111
// Emit firebase
1212
const dispatch = createEventDispatcher();
1313
14-
// Set firebase context
15-
firebase = firebase || window.firebase;
16-
setContext("firebase", firebase);
14+
// Must be a function to ensure changes after initialization are caught
15+
setContext("firebase", {
16+
getFirebase: () => firebase
17+
});
18+
1719
1820
onMount(() => {
21+
22+
// Set firebase context from window if needed
23+
firebase = firebase || (window && window.firebase);
24+
1925
if (!firebase) {
2026
throw Error(
2127
"No firebase app was provided. You must provide an initialized Firebase app or make it available globally."

src/helpers.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { getContext } from 'svelte';
22

3-
4-
export function getApp() {
5-
return getContext('firebase');
3+
export function getFirebaseContext() {
4+
const { getFirebase } = getContext('firebase');
5+
return getFirebase();
66
}
77

88
// Validates end-user has setup context and imported proper modules into the Svelte app
99
export function assertApp(pkg) {
1010

11-
const app = getApp();
11+
const app = getFirebaseContext();
1212

1313
if (!app) {
1414
throw new Error(`Missing Firebase app in context. Are you inside a 'FirebaseApp' component?`)

0 commit comments

Comments
 (0)