Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useSubject.md
1---2category: '@RxJS'3---45# useSubject67Bind an RxJS [`Subject`](https://rxjs.dev/guide/subject) to a `ref` and propagate value changes both ways.89## Usage1011<!-- TODO: import rxjs error if enable twoslash -->1213```ts no-twoslash14import { useSubject } from '@vueuse/rxjs'15import { Subject } from 'rxjs'1617const subject = new Subject()1819// setup()20const subjectRef = useSubject(subject)2122// Changes to subjectRef.value will be pushed to the subject23subjectRef.value = 'new value'2425// Values emitted by the subject will update subjectRef26subject.next('from subject')27```2829### With BehaviorSubject3031When using a `BehaviorSubject`, the returned ref is initialized with the subject's current value and the type does not include `undefined`:3233```ts no-twoslash34import { useSubject } from '@vueuse/rxjs'35import { BehaviorSubject } from 'rxjs'3637const subject = new BehaviorSubject('initial')3839// setup()40const subjectRef = useSubject(subject) // Ref<string>, not Ref<string | undefined>41console.log(subjectRef.value) // 'initial'42```4344### Error Handling4546If you want to add custom error handling to a Subject that might error, you can supply an optional `onError` configuration. Without this, RxJS will treat any error in the supplied observable as an "unhandled error" and it will be thrown in a new call stack and reported to `window.onerror` (or `process.on('error')` if you happen to be in node).4748```ts no-twoslash49import { useSubject } from '@vueuse/rxjs'50import { Subject } from 'rxjs'5152const subject = new Subject()5354// setup()55const subjectRef = useSubject(subject, {56onError: (err) => {57console.log(err.message) // "oops"58},59},)60```6162## Type Declarations6364```ts65export interface UseSubjectOptions<I = undefined> extends Omit<66UseObservableOptions<I>,67"initialValue"68> {}69export declare function useSubject<H>(70subject: BehaviorSubject<H>,71options?: UseSubjectOptions,72): Ref<H>73export declare function useSubject<H>(74subject: Subject<H>,75options?: UseSubjectOptions,76): Ref<H | undefined>77```78