Redux Toolkit - 使用 RTK 查询设置初始状态

Redux Toolkit - Setting initial state using RTK Query

我正在尝试使用 RTK 查询通过异步函数设置我的 contactSlice.ts 的初始状态。

我已经阅读了文档并在网上进行了搜索,但没有找到适合该问题的解决方案。

contactsAPI.ts:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { Contact } from '../models/contact.model';

export const contactsApi = createApi({
    reducerPath: "contactsApi",
    baseQuery: fetchBaseQuery({ baseUrl: "http://localhost:3006/" }),
    tagTypes: ['Contact'],
    endpoints: (builder) => ({
        contacts: builder.query<Contact[], void>({
            query: () => '/contacts',
            providesTags: ['Contact']
        }),
        contact: builder.query<Contact, string>({
            query: (id) => `/contacts/${ id }`,
            providesTags: ['Contact']
        }),
        addContact: builder.mutation<{}, Contact>({
            query: contact => ({
                url: '/contacts',
                method: 'POST',
                body: contact    
            }),
            invalidatesTags: ['Contact']
        }),
        updateContact: builder.mutation<void, Contact>({
            query: ({id, ...rest}) => ({
                url: `/contacts/${ id }`,
                method: 'PUT',
                body: rest
            }),
            invalidatesTags: ['Contact']
        }),
        deleteContact: builder.mutation<void, string>({
            query: (id) => ({
                url: `/contacts/${ id }`,
                method: 'DELETE',
            }),
            invalidatesTags: ['Contact']
        })
    })
})

export const {
    useContactsQuery,
    useContactQuery,
    useAddContactMutation,
    useUpdateContactMutation,
    useDeleteContactMutation
} = contactsApi;

contactSlice.ts:

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Contact } from '../models/contact.model';
import type { RootState } from '../store';

// Define a type for the slice state
interface ContactState {
    value: Contact[]
}

// Define the initial state using that type
const initialState: ContactState = {
    value: //enter async function here
}

export const counterSlice = createSlice({
    name: 'contact',
    // `createSlice` will infer the state type from the `initialState` argument
    initialState,
    reducers: {}
})

export default counterSlice.reducer

我想使用 contactsAPI.ts 中的 useContactsQuery 设置 initialState 值,但我不知道如何做到异步并启用 cathing 错误。

您可以像 example 中那样使用 extraReducers 来实现此操作。

虽然您应该考虑而不是这样做以获得更一致的Single Source of Truth

相反,您应该使用您的 rtk API 作为将失效并在需要时自动重新获取的存储。

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { Contact } from '../models/contact.model';
import type { RootState } from '../store';

// Define a type for the slice state
interface ContactState {
    value: Contact[]
}

// Define the initial state using that type
const initialState: ContactState = {
    value: //enter async function here
}

export const counterSlice = createSlice({
    name: 'contact',
    // `createSlice` will infer the state type from the `initialState` argument
    initialState,
    reducers: {},
   extraReducers: (builder) => {
      builder.addMatcher(
        api.endpoints.contacts.matchFulfilled,
        (state, { payload }) => {
           state = payload
       }
    )
  },
})

export default counterSlice.reducer

查看更多:

RTK Query: dispatch inside query or mutations - github