mongodb 如何使用Apollo的useQuery使用Redux Toolkit设置initialState?

xnifntxz  于 2023-11-17  发布在  Go
关注(0)|答案(2)|浏览(159)

我正在尝试调用useQuery钩子(在功能组件之外不允许的东西),在一个redux工具包切片中。这是可行的吗,也许使用masyncThunk或一些类似的方法?我的应用程序是用MERN堆栈构建的,所以我的数据库是MongoDB,我使用Graphql来获取数据。(在这个例子中我忽略了reducer,因为我只关注获取数据并将其设置为初始状态。)

import { useQuery } from "@apollo/client";
import { createSlice } from "@reduxjs/toolkit";
import { GET_USER_SETTINGS } from "../graphql/queries/settingsQueries";

const { loading, error, data } = useQuery(GET_USER_SETTINGS);

const { gridView } = data.settings;

const initialState = {
   gridView,
};

const settingsSlice = createSlice({
  name: "settings",
  initialState,
  reducers: {
    setGridViewOff(state) {
      state.gridView = false;
    },
    setGridViewOn(state) {
      state.gridView = true;
    }, 
},
});

export const { setGridViewOff, setGridViewOn } = settingsSlice.actions;

export default settingsSlice.reducer;

字符串

mrphzbgm

mrphzbgm1#

你说的没错,你不能从Redux切片代码中调用useQuery。我在这里建议使用一些“未定义”的初始gridView状态,并使用useEffect钩子来“初始化”gridView值。
类似于下面的例子:

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
   gridView: undefined,
};

const settingsSlice = createSlice({
  name: "settings",
  initialState,
  reducers: {
    initializeGridView: (state, action) => {
      state.gridView = action.payload;
    },
    setGridViewOff(state) {
      state.gridView = false;
    },
    setGridViewOn(state) {
      state.gridView = true;
    }, 
  },
});

export const {
  initializeGridView,
  setGridViewOff,
  setGridViewOn
} = settingsSlice.actions;

export default settingsSlice.reducer;

个字符
在你的应用中靠近Redux所在根目录的地方调用useInitializeGridView,例如在ReactTree中的Redux Provider组件下。任何依赖于state.settings.gridView值的UI都应该首先检查它是否已定义,然后使用定义的true/false值。

cqoc49vn

cqoc49vn2#

你可以通过创建一个Redux Thunk动作来获取数据并设置初始状态,然后从你的组件中调度Redux Thunk动作来处理这个问题。

示例

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { useQuery } from "@apollo/client";
import { GET_USER_SETTINGS } from "../graphql/queries/settingsQueries";

export const fetchUserSettings = createAsyncThunk("settings/fetchUserSettings", async (_, { dispatch }) => {
  try {
    const { data } = await useQuery(GET_USER_SETTINGS);
    const gridView = data.settings.gridView;

    return { gridView };
  } catch (error) {
    throw error;
  }
});

const initialState = {
  gridView: null,
};

const settingsSlice = createSlice({
  name: "settings",
  initialState,
  reducers: {
    setGridViewOff(state) {
      state.gridView = false;
    },
    setGridViewOn(state) {
      state.gridView = true;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchUserSettings.fulfilled, (state, action) => {
      state.gridView = action.payload.gridView;
    });
  },
});

export const { setGridViewOff, setGridViewOn } = settingsSlice.actions;

export default settingsSlice.reducer;

字符串

相关问题