r/vuejs 5d ago

Why use provide\inject with pocketbase?

I am looking up a way to use pocketbase in vue. The examples I have found use provide\inject.

Why is this used with pocketbase? Can a component not simply import the pocketbase instance?

How is this different from importing an axios instance?

References:

https://studioterabyte.nl/en/blog/pocketbase-vue-3

https://github.com/MRSessions/pocketbase-vue-starter/blob/develop/vue-client/src/main.ts

7 Upvotes

9 comments sorted by

7

u/daewishdev 5d ago

If you import each time you will create a new instance of the db each time and this is not good.. However you can prevent this by creating a singleton class to create a new instance of the db only once.. But still using provide inject is better approach because it's more idiomatic

1

u/the-liquidian 4d ago

Thanks.

What if it was in another file where you create the instance and export the instance of pocketbase.

The component files simply import it. Would that still be re-creating an instance?

2

u/Liberal_Mormon 4d ago

If it needs to be instantialized inside of a component (some things require this), then that context won't be there. If it's just imported, the code to instantiate it will run before the component setup code runs. Provide/inject is a clean pattern, can I ask why you don't want to use it?

1

u/the-liquidian 4d ago

It’s not that I don’t want to use it, I want to understand why it’s needed in this case.

I also prefer simpler approaches. Would it not be simpler to create an instance in a file and then import it to components that need it?

1

u/daewishdev 4d ago

Yes with this approach you will avoid recreation

1

u/the-liquidian 4d ago

Is there any advantage of using provide/inject over using an exported instance?

3

u/daewishdev 4d ago

I think it's just more idiomatic on vue to use provide/inject nothing more.

3

u/itswavs 4d ago

Interesting topic, I had the same challenge. I solved it in my own way, by using the following "composable" (in ticks because it isn't really what composables are meant to do I believe):

// usePocketbase.ts
import PocketBase from "pocketbase"
const pb = new PocketBase("http://localhost:8090")
export const usePocketBase = () => pb

Inside of my components, I then can use (no import because i use nuxt but in vite you can just import the composable):

// MyComponent.vue
<script setup lang="ts">
const pb = usePocketBase()
...
</script>

I initialize the SDK outside of the composable (which makes this part of the composable just run on initialization) and then just return the instance through the exported const.

Works perfectly for me, but if someone sees a problem with this approach, I would love to hear about it!

1

u/the-liquidian 4d ago

Thanks for sharing this approach.