Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

feat: change ssrRef implementation #26

Closed
mathe42 opened this issue May 5, 2020 · 7 comments
Closed

feat: change ssrRef implementation #26

mathe42 opened this issue May 5, 2020 · 7 comments
Assignees
Labels
enhancement New feature or request

Comments

@mathe42
Copy link
Collaborator

mathe42 commented May 5, 2020

🆒 SSR-Ref

Sorry pressed create to soon

@mathe42 mathe42 added the enhancement New feature or request label May 5, 2020
@mathe42 mathe42 changed the title feat: change ssrImplementation feat: change ssrRef implementation May 5, 2020
@mathe42 mathe42 closed this as completed May 5, 2020
@mathe42
Copy link
Collaborator Author

mathe42 commented May 5, 2020

Was thinking about useing customRef but this does not exists in @vue/composition-api only in @vue/reactivity.

import {
  onServerPrefetch,
  getCurrentInstance,
  customRef
} from 'nuxt-composition-api'

export function ssrRef<T>(value: T, key: string) {
  if (process.client) {
    const serverValue = (window as any).__NUXT__?.ssrRefs?.[key]
    if (serverValue !== undefined) {
      value = serverValue
    }
  }

  return customRef<T>((track: () => void, trigger: () => void) => {
    return {
      get() {
        track()
        return value
      },
      set(newValue: T) {
        value = newValue
        trigger()

        if (process.server) {
          onServerPrefetch(() => {
            const vm = getCurrentInstance()!

            if (!vm!.$ssrContext.nuxtState.ssrRefs) {
              vm!.$ssrContext.nuxtState.ssrRefs = {}
            }

            vm!.$ssrContext.nuxtState.ssrRefs[key] = value
          })
        }
      }
    }
  })
}

@danielroe
Copy link
Member

@mathe42 Now I'm really curious 😛

@danielroe
Copy link
Member

Very interesting idea. 👍

@mathe42
Copy link
Collaborator Author

mathe42 commented May 5, 2020

Thanks :D

@danielroe
Copy link
Member

Might be possible with computed with a custom setter. Not sure of the performance implications. 🤔 Is there a shortcoming of the current approach you're aware of?

@mathe42
Copy link
Collaborator Author

mathe42 commented May 5, 2020

In Vue3 I want to use shallowRef on server side and ref on client side to reduce Proxy creation on the server.

Maybe some sort of abstract function to interact with $ssrContext.nuxtState and window.__NUXT__ would be nice.

Like:

type func = (rootKey: string) => {
   client<T>: (key: string, initValue: T) => T, //get SSR data if exists
   server: (key: string, value: any) => void //set SSR data
}

@mathe42
Copy link
Collaborator Author

mathe42 commented May 5, 2020

see #28

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants