GithubHelp home page GithubHelp logo

markthree / vue-use-state-effect Goto Github PK

View Code? Open in Web Editor NEW

This project forked from lukasborawski/vue-use-state-effect

0.0 2.0 0.0 424 KB

Fast and small library, built on top of the native Vue.js API that will provide a safe and sharable (across the app) state for your local composables and functions.

Home Page: https://www.npmjs.com/package/vue-use-state-effect

License: ISC License

Shell 1.16% JavaScript 24.36% TypeScript 45.62% HTML 2.54% Vue 26.32%

vue-use-state-effect's Introduction

Vue Use State Effect

npm version npm version npm version

CAUTION: Built and tested for/with Vue 3 and/or Nuxt 3.

Fast and small library (composable), built on top of the native EffectScope Vue 3 API that will provide safe and sharable (across the app) state for your local composables and functions. It might be a good replacement / alternative for Vuex or Pinia state management, if you need smaller and less extensive solution.

Check out the Stackblitz Nuxt 3 demo here. ๐Ÿš€

Motivation / Story


You can read all about the technical background and all the details in this article.

Check out below how to use it, provided examples and demos where you can see it in action. Any questions, problems, errors? Please check out the Q&A section first, then if you still will be unhappy add a new Issue. Thanks and Enjoy!

Installation


Install the package:

$ npm i vue-use-state-effect --save
# or
$ yarn add vue-use-state-effect

Usage


Create your local composable with some state and pass it to the useStateEffect.

import { useStateEffect } from 'vue-use-state-effect'

const composable = () => {
  /* your composable logic here */
}

export const useSharedComposable = useStateEffect(composable)

Interface (TypeScript).

interface UseStateEffectConfig {
  readonly name?: string | null
  readonly destroy?: boolean
  readonly debug?: boolean
}

export function useStateEffect<T extends (...args: any[]) => any>(composable: T, config?: UseStateEffectConfig): () => {
  [keyof in string | 'state']: ReturnType<T>
}

Please check the example for some wider perspective.

Configuration (API)


You can use some options to define your usage preferences.

name

  • type: String | 'state'

  • default: state

  • description: name of composable state object that you'll be referring to inside your components, if not defined by default your state object will get state key, please note that it's not read automatically and that's because of application build mode functions name-spaces formatting

debug

  • type: Boolean

  • default: false

  • description: if set to true it will turn on the debug mode, you will be able to see the shared composable body

  • tip: you can turn it on for the development mode

    { debug: process.env.NODE_ENV === 'development' }

destroy

  • type: Boolean

  • default: false

  • description: if set to true composable state will be destroyed after component onBeforeUnmount hook

Here is a simple example of how to use it (the whole config).

export const useComposable = useStateEffect(useSharedComposable, {
  name: 'useSharedComposable',
  debug: true,
  destroy: true,
})

More about it in the example that you can find below.

Example


Here you can find a simple usage example that was also covered within the demo projects which you can discover in this repository (one for Vue and one for Nuxt). Check out the Demo section below for more details.

OK - first - let's create a local composable.

/* composables/useSharedState.ts */

import { ref } from 'vue'

const sharedState = () => {
  const state = ref({
    test: '๐Ÿš€ Initial state value.',
  })
  const updateState = () => {
    state.value = {
      test: '๐ŸŒ Updated state value.',
    }
  }
  return {
    state,
    updateState,
  }
}

What you can see here is a simple state ref object to which we've passed test string. Then we have method that will update this state. Please notice that we're not exporting this method, we're not creating any external or global state objects, everything is locked inside the local composition function.

Now, import and use the vue-use-state-effect composable.

/* composables/useSharedState.ts */

import { useStateEffect } from 'vue-use-state-effect'

/* you composable logic  */

export const useSharedState: any = useStateEffect(sharedState, {
  name: 'sharedState',
  debug: true,
  destroy: false,
})

OK, great. Let's use it along with some page / component. Create one e.g. home.vue.

<!-- Home Page | home.vue -->

<template>
  <div>{{ test }}</div>
  <button @click="updateState">update state</button>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useSharedState } from '@composables/useSharedState'

const {
  sharedState: { state, updateState },
} = useSharedState()

const test = computed(() => state.value.test) // '๐Ÿš€ Initial state value.',
</script>

Please note that we're using <script setup> notation here, you can find more about it in this article. Right, what you can see here is that we're importing our newly shared composable with state data. With the state we have the updateState method, that it will update the state. Name of the parent object (sharedState) was defined within the configuration. Now you can create new page / component and read saved or updated state along with the different context. Like this.

<!-- New Page | new.vue -->

<template>
  <div>{{ test }}</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useSharedState } from '@composables/useSharedState'

const {
  sharedState: { state },
} = useSharedState()
const test = ref(state.value.test) // '๐ŸŒ Updated state value.',
</script>

Tip: because of asynchronously created components (especially in Nuxt), if you want to destroy state after the component or page were unmounted - where this state was used - it's good to listen for the new one within the onMounted hook.

Demo


Want to check and test it in action?

Check out the Stackblitz Nuxt 3 demo here. ๐Ÿš€

You can also try out locally with the simple apps (Vue 3 and Nuxt 3) in the demo folders. You can fire it up manually or from the main folder of this repository, by using these two commands*.

# vue demo
yarn demo:vue
# nuxt demo
yarn demo:nuxt

*using yarn here, but you can still change it to npm


API Reference: Check out the types for API definitions.

Contribution: Please add Pull Request or Issue to introduce some changes or fixes.

Support: Want to support? Buy me a coffee or sponsor me via GitHub.

Buy Me a Coffee

vue-use-state-effect's People

Contributors

lukasborawski avatar markthree avatar

Watchers

James Cloos avatar  avatar

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.