Giter Club home page Giter Club logo

vue-sanity's Introduction

๐ŸŸข vue-sanity

Sanity integration for VueJS

Composition API methods to incorporate Sanity into a Vue project.

Features

  • ๐Ÿ—„ Caching: Query results are cached.
  • ๐Ÿ’ช TypeScript: Written in TypeScript.
  • ๐Ÿ“ก Real-time: Supports previews using Sanity listening mode.
  • ๐Ÿ–‡ Composition API: Vue3/Vue2 support using vue-demi.
  • ๐Ÿ“ SSR support: Compatible with server-side rendering with Nuxt and vanilla Vue.

Quick Start

If you are using Vue 2, then this project requires usage of @vue/composition-api. Make sure you've set that up correctly first. If you're using Vue 3, no extra steps are required.

First install vue-sanity:

yarn add vue-sanity

# or npm

npm install vue-sanity --save

Now configure Sanity in your root component:

import { useSanityClient } from 'vue-sanity'

export default {
  name: 'App',
  setup() {
    useSanityClient({
      projectId: 'myprojectid',
      dataset: 'production',
      useCdn: process.env.NODE_ENV === 'production',
    })
  },
}

Then you can use useSanityFetcher in any child component:

<template>
  <div>
    <h1>
      {{ title }}
    </h1>
  </div>
</template>

<script>
import { useSanityFetcher } from 'vue-sanity'

export default {
  setup() {
    const { data: title } = useSanityFetcher('*[_type == "article"][0].title')

    // OR use a factory function
    const { data: title } = useSanityFetcher(
      () => `*[slug.current == ${slug.value}][0].title`
    )

    return { title }
  },
}
</script>

API

useSanityClient

  • config

    These are the options required by @sanity/client. For more details, see the Sanity docs.

  • supportPreview

    In addition to the config you would normally pass to @sanity/client, you can pass a boolean as a second parameter for whether to create a preview client. (Used currently only when listening to real-time data updating.)

  • defaultOptions

    You may also pass an object of options that will be passed to any queries you make using useSanityFetcher, although of course they will be overridden by any specific options you pass to useSanityFetcher.

Example

import { useSanityClient } from 'vue-sanity'

export default {
  setup() {
    useSanityClient(
      {
        projectId: 'myprojectid',
        dataset: 'production',
        useCdn: process.env.NODE_ENV === 'production',
      },
      true // will now create a preview client for use elsewhere
    )
  },
}

useSanityFetcher

  • query

    A function that retuns a query string. If the return value changes, a new Sanity query will be run and the return value automatically updated.

  • initialValue You can provide an initial value for the query result (which will be returned before query completes).

  • mapper

    You can provide a function to transform the query result.

  • options

    You can also provide an object of additional options.

    • listen: true, false or an object of options to pass to client.listen (defaults to false)
    • strategy: strategy for fetching. Defaults to both.
      • :server: will not refetch if the cache has been populated on SSR
      • :client: will disable SSR fetching entirely
      • :both: will fetch on server and refetch when page is loaded
    • deduplicate: Whether to de-duplicate identical fetches. If set to true, additional fetches will not run unless made after the previous request errors or succeeds. If set to a number, additional fetches will run, but only after this many milliseconds after the previous fetch began.

useSanityQuery

If you are using sanity-typed-queries to define your schema, this is a helper function to reduce boilerplate and explicit typing.

import { useSanityQuery } from 'vue-sanity'
import { builder } from './cms/schemas/author.js'

export default {
  setup() {
    // title will be typed as Ref<string | null>, with null as a default value
    const { data: title } = useSanityQuery(builder.pick('name').first())

    // authors will be typed as Ref<string[]>, with an empty array as a default value
    const { data: authors } = useSanityQuery(builder.pick('name'))

    return { title, authors }
  },
}

Example

import { useSanityClient } from 'vue-sanity'

export default {
  setup() {
    const { data: title } = useSanityFetcher(
      // query
      () => `*[_type == "article"][0].title`,
      // initial value
      'Title - Default',
      // mapper
      result => `Title - ${result}`,
      // options
      {
        listen: true,
        clientOnly: true,
      }
    )

    return { title }
  },
}

Usage with TypeScript

You can type the return value of useSanityFetcher in several ways.

// data will be typed as Ref<string | null>
const { data } = useSanityFetcher<string>(
  () => `*[_type == "article"][0].title`
)
// data will be typed as Ref<string | number> as a number has been provided as a default value
const { data } = useSanityFetcher<string, number>(
  () => `*[_type == "article"][0].title`,
  3
)
// data will be typed as Ref<boolean | { value: string }> as it can infer the type
const { data } = useSanityFetcher(
  () => `*[_type == "article"][0].title`,
  true,
  (result: string) => ({ value: result })
)

Inspirations

Projects I've found helpful are:

Contributors

This has been developed to suit my needs but additional use cases and contributions are very welcome.

License

MIT License - Copyright ยฉ Daniel Roe

vue-sanity's People

Contributors

aadgrant avatar danielroe avatar jacenre avatar lgtm-com[bot] avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vue-sanity's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update devdependency vite to v4.5.3 [security]
  • chore(deps): update devdependency @types/memory-fs to v0.3.7
  • chore(deps): update devdependency unbuild to v0.9.4
  • chore(deps): update devdependency vue to v2.7.16
  • chore(deps): update test packages (@vitest/coverage-c8, vitest)
  • chore(deps): update vue monorepo to v2.7.16 (vue-server-renderer, vue-template-compiler)
  • chore(deps): lock file maintenance

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @sanity/image-url to v1.0.2
  • chore(deps): update dependency sanity-typed-queries to v0.9.5
  • chore(deps): update pnpm to v7.33.7
  • chore(deps): update dependency @sanity/client to v3.4.1
  • chore(deps): update devdependency eslint to v8.57.0
  • chore(deps): update devdependency expect-type to v0.19.0
  • chore(deps): update devdependency semver to v7.6.0
  • chore(deps): update devdependency typescript to v5.4.5
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update all linters (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser, eslint, eslint-config-prettier, eslint-plugin-prettier, prettier)
  • chore(deps): update codecov/codecov-action action to v4
  • chore(deps): update devdependency conventional-changelog-conventionalcommits to v8
  • chore(deps): update devdependency husky to v9
  • chore(deps): update devdependency lint-staged to v15
  • chore(deps): update devdependency unbuild to v2
  • chore(deps): update github/codeql-action action to v3
  • chore(deps): update pnpm to v9
  • chore(deps): update release-it (major) (@release-it/conventional-changelog, release-it)
  • chore(deps): update test packages (major) (happy-dom, vitest)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/checkout v3
  • actions/setup-node v3
  • codecov/codecov-action v3
.github/workflows/codeql.yml
  • actions/checkout v3
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
npm
package.json
  • @sanity/client ^3.3.2
  • @sanity/image-url ^1.0.1
  • minify-groq ^1.0.0
  • sanity-typed-queries ^0.9.0
  • vue-demi ^0.14.0
  • @release-it/conventional-changelog 5.1.1
  • @types/memory-fs 0.3.3
  • @typescript-eslint/eslint-plugin 5.62.0
  • @typescript-eslint/parser 5.62.0
  • @vitest/coverage-c8 0.31.4
  • @vue/composition-api 1.7.2
  • @vue/test-utils 1.3.6
  • conventional-changelog-conventionalcommits 5.0.0
  • eslint 8.49.0
  • eslint-config-prettier 8.10.0
  • eslint-plugin-prettier 4.2.1
  • expect-type 0.16.0
  • flush-promises 1.0.2
  • happy-dom 9.20.3
  • husky 8.0.3
  • lint-staged 13.3.0
  • memory-fs 0.5.0
  • pinst 3.0.0
  • prettier 2.8.8
  • release-it 15.11.0
  • semver 7.5.4
  • typescript 5.2.2
  • unbuild 0.7.2
  • vite 4.4.9
  • vitest 0.31.4
  • vue 2.6.14
  • vue-server-renderer 2.6.14
  • vue-template-compiler 2.6.14
  • @vue/composition-api 1.7.2
  • vue ^2.0.0 || >=3.0.0-rc.0
  • minimist >=1.2.5
  • pnpm 7.33.6

  • Check this box to trigger a request for Renovate to run again on this repository

help: Module '"vue-sanity"' has no exported member 'useSanityClient'.

๐Ÿ“š What are you trying to do? Please describe.
When using the vie-sanity client inside a Vite + TS project, useSanityClient doesn't seem to be exported from the package.

import { useSanityClient } from 'vue-sanity'
Module '"vue-sanity"' has no exported member 'useSanityClient'.ts(2305)

๐Ÿ” What have you tried?
N/A

โ„น๏ธ Additional context
"vue": "^3.0.5",
"vue-sanity": "^0.10.6"

Trying to use this with Vue 3 and Vite

๐Ÿ“š What are you trying to do? Please describe.
I have a Vue 3 web app that builds with Vite and want to draw in data from my Sanity graph. Vite is an ESM-only build system that doesn't know what require means, so it blows up when I try to use this lib to spin up the Sanity Client and fire the fetcher.

๐Ÿ” What have you tried?
I've tried cloning the next branch and changing the requires to imports. I'm not yet able to get it to build locally. It says it's missing lib/*. I can offer a more precise account of these attempts if helpful.

I have also tried to find a way to shoehorn Vite into CommonJS compatibility or interpreting requires, but that's a pretty strong nope.

โ„น๏ธ Additional context
Sanity is awesome and I really appreciate you offering this library. Would be rad to get it integrated with Vite, cuz that's super fast.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (:automergeEarlyMondays). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

help: Disable chaching.

๐Ÿ“š What are you trying to do? Please describe.
I've come across issues with caching during dev. I feel there is a 45 seconds delay until i get updates from the cms to show up on nuxt. In general caching is perfect, but for quick tryouts i'd need to turn it off. How can I do that?

๐Ÿ” What have you tried?
In the documentation I only found how to switch where the caching should happen, but not how to turn it off completely.

Thank you!

feat: Vite-SSG support

๐Ÿ†’ Your use case
Correctly prefetching when using vite-ssg. Currently it cannot detect it and will run into errors (window is not defined).
A small change could fix it.

๐Ÿ†• The solution you'd like
Very simply check if vite-ssg is currently generating the pages, and if so request it.
PR already exists for that: #220

๐Ÿ” Alternatives you've considered

  • Replacing the check for the $isServer variable with typeof window !== 'undefined'
  • Figuring out how to inject the $isServer variable as the current code looks for that to determine if the call is server side or client side.
    This would be impossible without changing the Vite-SSG source code. Just changing a single line here would already solve it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.