Socket
Socket
Sign inDemoInstall

vue-3-firestore

Package Overview
Dependencies
1
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    vue-3-firestore

An easy way to interact with Firestore using vue 3 and the composition-api


Version published
Weekly downloads
7
decreased by-36.36%
Maintainers
1
Created
Weekly downloads
 

Readme

Source

vue-3-firestore

An easy way to interact with Firestore using vue 3 and the composition-api.

  • Get started
  • Usage
  • Options
  • Return values
  • Examples

Examples:

Get started

yarn add vue-3-firestore

in your .vue file

<template lang="html">
  <p>{{ data }}</p>
</template>

<script lang="ts">
import { defineComponent, ref } from '@vue/composition-api'
import useFirestore from 'vue-3-firestore'
export default defineComponent({
  setup() {
    const uid = ref('1')

    const { data, loading } = useFirestore({
      queryType: 'doc',
      type: 'watch',
      path: 'collection/$uid',
      variables: {
        uid
      }
    })

    return {
      data
    }
  }
})
</script>

<style lang="scss" scoped></style>

Usage

const results = useFirestore<ReturnDataType>(options)

Options

paramtyperequired?defaultdescription
queryTypestringtrueThe type of this query - 'collection' or 'doc'
typestringtrueThe type of the get function - 'watch' or 'get'. 'get' does a single get() from firestore. 'watch' watches for document or collection changes and updates the data recieved
pathstringtruePath to the document or collection in firestore. Use $variableName to insert reactive variable data into the path. If the path includes variables, the options object must include a 'variables' key
variablesObjectfalseVariables that should be used to construct the path to the document or collection in firestore. If a variable changes the path, data will be re-fetched. Variable values should be a vue ref. Variable keys should match those in the path string
debouncenumberfalse200The debounce amount in milliseconds that should be waited between a path change and getting the data from firestore. Useful to change if a variable is bound to a text input. Defaults to 200
initialLoadingbooleanfalsetrueThe initial state of the loading return value. Defaults to true. Setting to false could be helpful in manual mode
manualbooleanfalsefalseWhen in manual mode, data will not automatically be fetched or watched initially or on path change. It will be up to you to call the getData or watchData function.
onErrorfunctionfalseconsole.errorExposes a function to customise error handling. Defaults to console.error(e)
queryfunctionfalseExposes a function to extend the firestore query for the collection eg: add a '.where()' function or '.limit()'. The returned Query object will be used to get or watch data
mutatefunctionfalseExposes a function to mutate the data that is fetched from firestore. The mutated data will be returned as 'mutatedData'
onRecievefunctionfalseExposes a hook for when a collection is recieved. Provides access to the recieved data and mutated data

Return values

paramtypedescription
dataRef<T | T[] | null>The data returned from the collection as a reactive array or an ampty array if no data has been fetched yet
loadingRef<boolean>The loading state of the data fetch. Will be true when an async data fetch operation is happening. Works reactively as expected.
recievedRef<boolean>A reactive boolean value to indicate if data has been recieved yet. Will be false as soon as data has been recieved and will stay false thereafter.
pathReplacedComputedRef<string>A reactive string of the path with $variables replaced with the true variable value from the 'variables' input object
mutatedDataRef<M | null>Reactive mutated data returned from the mutate() function. If no mutate function is passed, will be equal to 'data'. Will be null until initialised and 'recieved' === true
firestoreRefComputedRef<CollectionRef | Docref>A reactive computed prop that returns the firestore collection reference query
firestoreQueryComputedRef<Query>A reactive computed prop that returns the firestore Query if the 'query' input function is used, else it will be null
updateDoc(updates: Partial<T>) => Promise<void>Exposes a method for updating the doc via the current firestore DocumentReference. Uses the firestore().doc(pathReplaced).set() function with the { merge: true } options. This way, it can be used to set a new doc as well as update an existing
deleteDoc() => Promise<void>Exposes a method for deleting the doc via the current firestore DocumentReference - firestore().doc(pathReplaced).delete()
watchData() => voidExposes a function to initiate a firestore document/collection listener via the onSnapshot method.
stopWatchData() => voidExposes a function for tearing down a firestore onSnapshot listener. Will be called on the onUnmounted hook of this component regardless of the manual mode setting.
getData() => Promise<{ data: T; mutatedData: M | null }>getData provides a function for getting data from firestore. firestore().doc(${path}).get

Examples

All of the examples below are within the context of the Vue composition api setup() function. eg:

import { defineComponent, ref } from '@vue/composition-api'
import useFirestore from 'vue-3-firestore'
export default defineComponent({
  setup() {
    // code examples
  }
})

This will save these docs from having a load of boiler 😅

Get Doc (without variables)

const { data, loading } = useFirestore({
  type: 'get',
  queryType: 'doc',
  path: 'collection/doc'
})
return { data, loading  }

Get Doc

const uid = ref('1')
const { data, loading  } = useFirestore({
  type: 'get',
  queryType: 'doc',
  path: 'collection/$id',
  variables: {
    id: uid
  }
})

return { data, loading  }

Get Collection (without variables)

const { data, loading  } = useFirestore({
  type: 'get',
  queryType: 'collection',
  path: 'collection/doc/subCollection'
})

return { data, loading  }

Get Collection

const uid = ref('1')
const { data, loading  } = useFirestore({
  type: 'get',
  queryType: 'collection',
  path: 'collection/$id/subCollection',
  variables: {
    id: uid
  }
})

return { data, loading  }

Watch Doc

const uid = ref('1')
const { data, loading  } = useFirestore({
  type: 'watch',
  queryType: 'doc',
  path: 'collection/$id',
  variables: {
    id: uid
  }
})

return { data, loading  }

Watch Collection

const uid = ref('1')
const { data, loading  } = useFirestore({
  type: 'watch',
  queryType: 'collection',
  path: 'collection/$id/subCollection',
  variables: {
    id: uid
  }
})

return { data, loading  }

With Typesctipt

interface UserType {
  firstName: string
  lastName: string
}

const uid = ref('1')
const { data: user, loading } = useFirestore<UserType>({
  queryType: 'doc',
  type: 'watch',
  path: 'users/$uid',
  variables: {
    uid
  }
})

const fullName = computed(() => {
  return `${user.value?.firstName} ${user.value?.lastName}`
})

return { user, loading }

With Typesctipt and Mutation of incoming data

interface UserType {
  firstName: string
  lastName: string
}
type fullName = string

const uid = ref('1')
const { mutatedData, loading } = useFirestore<UserType, fullName>({
  queryType: 'doc',
  type: 'watch',
  path: 'users/$uid',
  variables: {
    uid
  },
  mutate(data) {
    const { firstName, lastName } = data
    return `${firstName} ${lastName}`
  }
})

return { fullName: mutatedData, loading }

Manual mode get

interface UserType {
  firstName: string
  lastName: string
}

const uid = ref('1')
const { data: user, loading, getData } = useFirestore<UserType>({
  queryType: 'doc',
  type: 'get',
  path: 'users/$uid',
  variables: {
    uid
  },
  manual: true
})

const changeUserAndGetData = async(userId: string) => {
  uid.value = userId
  const newData = await getData()
  console.log(newData) // same as user.value
}

onMounted(() => {
  getData()
})

return { user, loading, changeUserAndGetData }

Manual mode watch

interface UserType {
  firstName: string
  lastName: string
}

const uid = ref('1')
const { data: user, loading, watchData, stopWatchData } = useFirestore<UserType>({
  queryType: 'doc',
  type: 'watch',
  path: 'users/$uid',
  variables: {
    uid
  },
  manual: true
})

const changeUserAndWatchData = async(userId: string) => {
  stopWatchData()
  uid.value = userId
  watchData()
}

return { user, loading, changeUserAndWatchData }

Update and Delete helpers

interface UserType {
  firstName: string
  lastName: string
}

const uid = ref('1')
const { data: user, loading, updateDoc, deleteDoc } = useFirestore<UserType>({
  queryType: 'doc',
  type: 'watch',
  path: 'users/$uid',
  variables: {
    uid
  }
})

const updatingUser = ref(false)
const updateUser = async (updates: Partial<UserType>) => {
  try {
    updatingUser.value = true
    await updateDoc(updates)
    updatingUser.value = false
  } catch (e) {
    updatingUser.value = false
    console.error(e)
  }
}

const deletingUser = ref(false)
const deleteUser = async (updates: Partial<UserType>) => {
  try {
    deletingUser.value = true
    await deleteDoc()
    deletingUser.value = false
  } catch (e) {
    deletingUser.value = false
    console.error(e)
  }
}

return { user, loading, updateUser, deleteUser }

Extending a query (order, where, limit)

interface UserType {
  firstName: string
  lastName: string
}

const { data: activeUsers, loading } = useFirestore<UserType>({
  queryType: 'collection',
  type: 'watch',
  path: 'users',
  query(collectionRef) {
    return collectionRef.where('status', '==', 'active').orderBy('lastName').limit(1)
  }
})

return { activeUsers, loading }

Roadmap

  • Make into vue plugin and inject into SetupContext

Keywords

FAQs

Last updated on 30 Dec 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc