Created
October 18, 2019 20:18
-
-
Save betiol/40fc291158978c9dccfacb26b7b70ea7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
import { database } from './'; | |
import UserStorage from '../shared/UserStorage'; | |
export async function save(data) { | |
const { uid } = await UserStorage.getUser(); | |
const request = await database.ref(`user/${uid}/decks`); | |
await request.push({ ...data }); | |
} | |
export function useFirebaseList(ref: string) { | |
const [list, setList] = useState([]); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(false); | |
useEffect(() => { | |
async function loadFirebaseData() { | |
const { uid } = await UserStorage.getUser(); | |
try { | |
setLoading(true); | |
await database.ref(`user/${uid}/${ref}`).on('value', snapshot => { | |
const val = snapshot.val(); | |
const data = Object.keys(val || []).map(key => ({ | |
key, | |
...val[key], | |
})); | |
setList(data); | |
setLoading(false); | |
}); | |
} catch (error) { | |
setError(error); | |
setLoading(false); | |
} | |
} | |
loadFirebaseData(); | |
}, [ref]); | |
return { list, error, loading }; | |
} | |
export function useDatabaseByKey(ref: string, key: string) { | |
const [only, setOnly] = useState({}); | |
const [error, setError] = useState(null); | |
const [loading, setLoading] = useState(false); | |
useEffect(() => { | |
async function loadFirebaseData() { | |
const { uid } = await UserStorage.getUser(); | |
try { | |
setLoading(true); | |
await database | |
.ref(`user/${uid}/${ref}/${key}`) | |
.on('value', snapshot => { | |
const val = snapshot.val(); | |
setOnly(val); | |
setLoading(false); | |
}); | |
} catch (error) { | |
setError(error); | |
setLoading(false); | |
} | |
} | |
loadFirebaseData(); | |
}, [ref, key]); | |
return { only, error, loading }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment