Skip to content

Instantly share code, notes, and snippets.

@mathieutu
Created October 19, 2020 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieutu/532a1091b215b7af84efe55b60425d91 to your computer and use it in GitHub Desktop.
Save mathieutu/532a1091b215b7af84efe55b60425d91 to your computer and use it in GitHub Desktop.
A test of a React style useState with vue3.
// not working
type SetFunction<T> = (newState: T | ((oldState: T) => T)) => void
export const useState = <T>(initial: T): [T, SetFunction<T>] => {
const state = ref(initial)
const setState: SetFunction<T> = (newState) => {
// @ts-ignore
state.value = typeof newState === 'function' ? newState(state.value) : newState
}
let stateValue = state.value
watchEffect(() => {
stateValue = state.value
console.log('watch', stateValue)
})
console.log('useState', stateValue)
return [stateValue as T, setState]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment