Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Vue composition that let you compose a ref with a function from values to refs.

License

NotificationsYou must be signed in to change notification settings

jfet97/vue-use-switch-map

Repository files navigation

npm i -S vue-use-switch-map

A Vue 3 composition package that exports:

  • useSwitchMap, a function to compose a ref with a function from values to refs
  • useSwitchMapO, a function to compose a ref with a function from values to objects containing refs

This package is designed for binding refs to Vue composition functions, which, in turn, may produce one or more refs.

It works with both Vue 3 and Vue 2 +@vue/composition-api because I'm usingvue-demi, and it is written in TypeScript.

The behaviour is similar to the RxJS switchMap operator.
The composition itself will produce a ref, calledswitchMappedRef. Each time the composed ref changes:

  1. the ref previously returned by the composed function will be discarded, so theswitchMappedRef will no longer be updated by its changes
  2. the composed function runs again, producing a new ref
  3. switchMappedRef is connected to this fresh ref, receiving its updates

Menu:

 

useSwitchMap

functionuseSwitchMap<T,U>(ref:Ref<T>,projectionFromValuesToRefs:(value:T,scf:SetCleanupFunction)=>Ref<U>):Ref<U>

useSwitchMap takes a ref and a function from values to refs, returning a ref that will see its value changed because of two main reasons: the composed function changes its returned ref's value, or the input ref's value has been changed.
The first case is not special at all, I'm sure you already use some Vue 3 composition functions that internally listen to some events, or use some timeouts, promises, etc. and therefore change the ref's value they return in response to those happenings.
The second case is more tricky, because a lot of stuff happens when the input ref's value is changed. The composed function is re-runned from scratch, producing a new refR. This ref is automagically substituted to the one thatuseSwitchMap has returned, in such a way that it will receive only the updates from the last refR produced.

A function is passed toprojectionFromValuesToRefs to let it set a cleanup function that will be called just beforeprojectionFromValuesToRefs is runned again.

example: mouse tracker

We want to track all the pointer positions after an initial click that starts the tracking. We want to be able to restart the tracking from scratch at each click.

Here it is:

import{useSwitchMap}from'vue-use-switch-map'import{ref}from'vue'// click handlingconstmouseClickPoisitonRef=ref({x:-1,y:-1})functionupdateMouseCLickPositionRef(x,y){mouseClickPoisitonRef.value.x=xmouseClickPoisitonRef.value.y=y}constclickListener=(clickEvent)=>{updateMouseCLickPositionRef(clickEvent.screenX,clickEvent.screenY)}// each time we click, mouseClickPoisitonRef is updatedwindow.addEventListener('click',clickListener)// positions trackingconstswitchMappedRef=useSwitchMap(mouseClickPoisitonRef,(initP,cleanup)=>{// do nothing until we clickif(initP.x===-1)returnref([])constpsRef=ref([{x:initP.x,y:initP.y}])constmoveListener=(moveEvent)=>{psRef.value.push({x:moveEvent.screenX,y:moveEvent.screenY,})}// add the new position inside the positions array refwindow.addEventListener('mousemove',moveListener)cleanup(()=>window.removeEventListener('mousemove',moveListener))returnpsRef})

HereswitchMappedRef will be a ref to an array that will be updated with the pointer positions after the first click. Each time we click somewhere on the screen, the function that tracks the mouse will be called again, soswitchMappedRef will be updated with a new, fresh array. We do use thecleanup function to set a function that will remove the event listener because, even if older listeners do not interfere withswitchMappedRef, we don't like memory leaks.

 

useSwitchMapO

A function likeuseSwitchMap is not enough in the case the composed function returns an object where each property is itself a ref. This is whyuseSwitchMapO was born.

functionuseSwitchMapO<T,Rextendsobject>(ref:Ref<T>,projectionFromValuesToRefs:(value:T,scf:SetCleanupFunction)=>R):R

example: fetch

Our goal is to compose the followinguseFetch Vue composition function with a ref, so that each time the ref is changed the function will refetch the data. ThisuseFetch function will return an object containing three refs: one that signal if the fetch is in a pending state, one for the resulting data and the last for a possible error message.

UsinguseSwitchMapO will be a breeze:

import{useSwitchMapO}from'vue-use-switch-map'import{ref,computed}from'vue'constuseFetch=(url)=>{constdataRef=ref(null)consterrorMessageRef=ref('')constisPendingRef=ref(true)fetch(url).then((response)=>response.json()).then((data)=>(dataRef.value=data)).catch((error)=>(errorMessageRef.value=error.message)).finally(()=>(isPendingRef.value=false))return{ dataRef, errorMessageRef, isPendingRef}}// for example, counterRef could be a propconstcounterRef=ref(0)functionincrementCounterRef(){counterRef.value++}consturlRef=computed(()=>`https://jsonplaceholder.typicode.com/todos/${counterRef.value}`)// here it isconst{ dataRef, errorMessageRef, isPendingRef}=useSwitchMapO(urlRef,useFetch)

As you can see, we don't have to worry about older fetch calls that may take longer than the last one, with the risk of having ourdataRef,errorMessageRef andisPendingRef changed by them.

Moreover, you can always use the cleanup function argument to set up a cleaup function, e.g. to stop an asynchronous computation:

constuseFetch=(url,cleanup)=>{constdataRef=ref(null)consterrorMessageRef=ref('')constisPendingRef=ref(true)constcontroller=newAbortController()constsignal=controller.signalfetch(url,{ signal}).then((response)=>response.json()).then((data)=>(dataRef.value=data)).catch((error)=>(errorMessageRef.value=error.message)).finally(()=>(isPendingRef.value=false))cleanup(()=>controller.abort())return{ dataRef, errorMessageRef, isPendingRef}}

In this case, though, the promise will rejects with anAbortError, so the magic ofuseSwitchMapO is still needed to prevent the problems we have just discussed.

 

Common needs

The Vue composition function depends on some static configuration

Let's say we have a Vue composition function like the following:

functionuseSomething(value,config[,cleanup]){// ...returnuseSomethingRef}

We want to bind such a function toaRef usinguseSwitchMap. How do we do that?

constmakeUseSomething=(config)=>(value[,cleanup])=>useSomething(value,config[,cleanup])constswitchMappedRef=useSwitchMap(aRef,makeUseSomething(config))

The composition involves more than one ref

Let's say we need to bind more than one ref to a composition function:

functionuseSomething(value,anotherValue[,cleanup]){// ...returnuseSomethingRef}constswitchMappedRef=useSwitchMap(aRef,anotherRef,useSomething)// that's not how 'useSwitchMap' works

How do we do that? Simple, we have to create an object ref:

constobjectRef=computed(()=>({value:aRef.value,anotherValue:anotherRef.value}))constswitchMappedRef=useSwitchMap(objectRef,(object[,cleanup])=>useSomething(object.value,object.anotherValue[,cleanup]))

 

Contribute

I've tried my best to test it, but I clearly suck at it. I've messed a lot with jest, fake timers and watchers without much success, therefore I was unable to express some advanced use cases that I had to personally test using home made solutions.Therefore, any contribution in this direction is really really appreciated 😊.

 

Notes

You can read more about this package in thisblog post.

About

A Vue composition that let you compose a ref with a function from values to refs.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp