更新redux reducer中的状态

gwo2fgha  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(119)

我有一个nextjs项目,我使用redux,我有reducers,我想在发送一个新的“任务”到服务器后,在reducers中更新我的initialstate,因为它可以帮助我立即向用户显示新的项目,但当我试图更新它时,给我未定义

import { createSlice } from "@reduxjs/toolkit";
import Cookies from "universal-cookie";
import { decode } from "jsonwebtoken";

const cookie = new Cookies();
const token = cookie.get("token");

export const initialState: any = {
  tasks: [],
  status: "idle",
};

// ========== Reducers ========== \\
// import { taskReducers } from "./reducers/task.reducer";

// ========== Thunks ========== \\
import { taskThunk } from "./thunks/task.thunk";
import { useGraphql } from "../../../helper/useGraphql";

const TaskSlice = createSlice({
  name: "task",
  initialState,
  reducers: {
    createTask: async (state, actions) => {
      const { id }: any = decode(token);

      try {
        const { taskName, taskTags } = actions.payload;

        const graphqlSchema = `
              mutation addTask($taskInput: TaskInput!) {
                  createTask(taskInput: $taskInput) {
                      _id
                      taskName
                      tags {
                          color
                          name
                      }
                  }
              }
          `;

        const variables = {
          taskInput: {
            taskName: taskName,
            tags: taskTags,
            userId: id,
          },
        };

        const { response } = await useGraphql(graphqlSchema, variables);

        const newElement = response.data.createTask;

        state.tasks = state.tasks.;

        return state;
      } catch (error) {
        console.log("Error in createTask reducer:", error);

        throw error;
      }
    },
  },
  extraReducers: (builder) => {
    builder.addCase(taskThunk.fulfilled, (state, actions) => {
      try {
        const tasks = actions.payload.getTasks;

        state.tasks = tasks;
        state.status = "success";
      } catch (error) {
        throw error;
      }
    });
  },
});

export const { createTask } = TaskSlice.actions;

export default TaskSlice.reducer;

字符串
这是useGraphql,我构建它来简化我的代码:

import axios from "axios";

export const useGraphql = async (schema: string, variables?: any) => {
  const graphqlSchema = {
    query: schema,
    variables: variables,
  };

  try {
    const sendRequest = await axios({
      url: "http://localhost:5000/",
      method: "POST",
      data: JSON.stringify(graphqlSchema),
      headers: {
        "Content-Type": "application/json",
      },
    });

    const response = sendRequest.data;

    return {
      response: response,
    };
  } catch (error) {
    throw error;
  }
};


这里我称函数

import { useState } from "react";

// =========== Components ========== \\
import Input from "../../../UIElements/input";
import Tags from "../../../UIElements/tags";
import Wrapper from "../wrapper.form";

// =========== Redux ========== \\
import { AppDispatch } from "../../../../redux/store";
import { useDispatch } from "react-redux";
import { createTask } from "../../../../redux/slices/tasks/index.slice";

const TaskCreatorForm = () => {
  const [taskName, setTaskName] = useState<String>("");
  const [taskTags, setTaskTags] = useState<Array<Object>>([]);

  const dispatch = useDispatch<AppDispatch>();

  const createTaskHandle = () => {
    const payload: any = {
      taskName,
      taskTags,
    };
    dispatch(createTask(payload));
  };

  return (
    <Wrapper admitFunction={createTaskHandle}>
      <Input
        placeholder="Task Name"
        type="text"
        label="Task Name"
        giveValue={setTaskName}
        requireSign={true}
      />
      <Tags
        giveValue={setTaskTags}
        coloration={true}
        placeholder="add tags"
        label="add Task"
      />
    </Wrapper>
  );
};

export default TaskCreatorForm;


下面是一个 Package 器,我在其中传递正确“admfunction”

import { useContext } from "react";

// =========== Components =========== \\
import { PrimaryButton } from "../../UIElements";

// =========== context =========== \\
import { modalContext } from "../../../context/modal.context";

const Wrapper = ({ children, admitFunction }: any) => {
  const { toggleModal } = useContext(modalContext);

  return (
    <div className="flex flex-col gap-6">
      {children}
      <div className="flex items-center justify-end w-full gap-4">
        <PrimaryButton
          color="transparent"
          className="!text-black"
          onClick={() => toggleModal("taskcreator")}
        >
          Close
        </PrimaryButton>
        <PrimaryButton onClick={admitFunction} className="shadow-sm">
          admit
        </PrimaryButton>
      </div>
    </div>
  );
};

export default Wrapper;


我曾尝试使用谷歌和chatGPT来解决这个问题,但没有效果

zlwx9yxi

zlwx9yxi1#

Reducer函数是纯 * 同步 * 函数。在异步操作中执行该工作,并分派一个操作来更新存储。将createTask操作转换为异步操作,例如另一个形实转换程序动作,并处理状态片的extraReducers中的解析值。

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Cookies from "universal-cookie";
import { decode } from "jsonwebtoken";

export const initialState: any = {
  tasks: [],
  status: "idle",
};

// ========== Thunks ========== \\
import { taskThunk } from "./thunks/task.thunk";
import { useGraphql } from "../../../helper/useGraphql";

export const createTask = createAsyncThunk(
  "task/createTask",
  async ({ taskName, taskTags }, ThunkAPI) => {
    const cookie = new Cookies();
    const token = cookie.get("token"); // <-- get token when action is called
    const { id }: any = decode(token);

    try {
      const graphqlSchema = `
        mutation addTask($taskInput: TaskInput!) {
          createTask(taskInput: $taskInput) {
            _id
            taskName
            tags {
              color
              name
            }
          }
        }
      `;

      const variables = {
        taskInput: {
          taskName,
          tags: taskTags,
          userId: id,
        },
      };

      const { response } = await useGraphql(graphqlSchema, variables);

      return response.data.createTask;
    } catch (error) {
      console.log("Error in createTask reducer:", error);

      return ThunkAPI.rejectWithValue(error);
    }
  },
);

const TaskSlice = createSlice({
  name: "task",
  initialState,
  extraReducers: (builder) => {
    builder
      .addCase(taskThunk.fulfilled, (state, action) => {
        try {
          const tasks = action.payload.getTasks;

          state.tasks = tasks;
          state.status = "success";
        } catch (error) {
          throw error;
        }
      })
      .addCase(createTask.fulfilled, (state, action) => {
        state.tasks.push(action.payload); // <-- add new task
      });
  },
});

export default TaskSlice.reducer;

字符串

相关问题