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

Alo*_*kov 6 reactjs redux redux-thunk react-redux redux-toolkit

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

我已阅读文档并在线搜索,但没有找到解决此问题的合适解决方案。

联系人API.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;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

Yed*_*shi 6

您可以通过使用 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
Run Code Online (Sandbox Code Playgroud)

查看更多:

RTK 查询:在查询或突变内调度 - github