vue-redux-hooks
v1.2.0
Published
Redux hooks for Vue
Downloads
52
Maintainers
Readme
vue-redux-hooks
Install
npm i redux vue-redux-hooks
yarn add redux vue-redux-hooks
API
ReduxStore
// store.ts
import { createStore, AnyAction } from 'redux'
function todos(state: string[] = [], action: AnyAction) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text])
default:
return state
}
}
export const store = createStore(todos, ['Use Redux'])
export type Store = typeof store
export type State = ReturnType<typeof todos>
export type Dispatch = typeof store.dispatch
// main.ts
import { createApp } from 'vue'
import { ReduxStore } from 'vue-redux-hooks'
import { store } from './store'
createApp(App).provide(ReduxStore, store).mount('#app')
Hooks
useStore
// api.ts
import { useStore } from 'vue-redux-hooks'
export default {
setup() {
const store = useStore<Store>()
const initialState = store.getState()
return { initialState }
},
}
useSelector
// api.ts
import { useSelector } from 'vue-redux-hooks'
export default {
setup() {
const todos = useSelector((state: State) => state)
const todosLength = useSelector((state: State) => state.length)
const lastTodo = computed(() => todos.value[todosLength.value - 1])
return { todos, lastTodo }
},
}
useDispatch
// api.ts
import { useDispatch } from 'vue-redux-hooks'
export default {
setup() {
const dispatch = useDispatch<Dispatch>()
const addTodo = (text: string) =>
dispatch({
type: 'ADD_TODO',
text,
})
return { addTodo }
},
}
RTK Query
createApi
// pokemonApi.ts
// Need to use the Vue-specific entry point to allow generating Vue hooks
import { createApi } from 'vue-redux-hooks'
import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import type { Pokemon } from './types'
// Define a service using a base URL and expected endpoints
export const pokemonApi = createApi({
reducerPath: 'pokemonApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
endpoints: (builder) => ({
getPokemonByName: builder.query<Pokemon, string>({
query: (name) => `pokemon/${name}`,
}),
}),
})
// Export hooks for usage in function components, which are
// auto-generated based on the defined endpoints
export const { useGetPokemonByNameQuery } = pokemonApi
// App.vue
import { toRefs, ref } from 'vue'
import { useGetPokemonByNameQuery } from './pokemonApi'
export default {
setup() {
const name = ref('Pikachu')
const skip = ref(false)
const query = useGetPokemonByNameQuery(name, {
refetchOnReconnect: true,
skip,
})
return { name, skip, ...toRefs(query) }
},
}