为什么我的useMutation在onClick时使用新日期()的旧值?



我的一个useMutation钩子变量(startDateTime)应该在我调用mutate函数时计算日期。更具体地说,当onClick事件被调用时。相反,我的mutate函数接受渲染时计算的日期。为什么呢?

我尝试将日期值存储在useState()钩子中,并获得相同的结果。

import { START_SESSION } from "@graphql/newSession";
import { useMutation } from "@apollo/client";
import { useAuth0 } from "@auth0/auth0-react";
import { clientDateToday, clientTimeNow } from "@modules/common/helper";
interface startNewSessionVariables {
id: number;
userName: string;
sessionTitle: string;
sessionCreateDate: string;
startdateTime: Date;
}
export const useStartSession = (sessionTitle: string) => {
const { user } = useAuth0();
let userName;
if (user) {
userName = user.name;
}
const [startNewSession, { data, loading, error }] = useMutation<{
startNewSession: startNewSessionVariables;
}>(START_SESSION, {
variables: {
userName,
sessionTitle,
sessionCreateDate: clientDateToday(),
startDateTime: clientTimeNow(),
},
});
return { startNewSession, result: data, loading, error };
};

高阶分量函数:

function startSession(): void {
//create new session in db
startNewSession();
//start the timer
toggleActive();
}

调用mutate函数的按钮:

import ToggleButton from "../common/ToggleButton";
interface toggleProps {
toggleIsActive: boolean;
toggleOnPause: boolean;
finishSession(): void;
startSession(): void;
}
const ToggleComponent = ({ toggleIsActive, toggleOnPause, finishSession, startSession }: toggleProps) => {
let buttonAction;
let buttonName: string;
if (toggleIsActive || toggleOnPause) {
buttonAction = finishSession;
buttonName = "End Session";
} else {
buttonAction = startSession;
buttonName = "Start";
}
return (
<div className="text-center mt-5">
<ToggleButton onToggle={buttonAction} btnName={buttonName} />
</div>
);
};
export default ToggleComponent;

您正在使用一组变量定义您的突变,但是稍后当您实际调用它时,您没有提供更新的集合。当您在其他组件中调用startMutation时,请包含更新后的变量:

() => startMutation({
variables: {
userName,
sessionTitle,
sessionCreateDate: clientDateToday(),
startDateTime: clientTimeNow(),
}
})

正如您可能已经猜到的那样,在最初创建突变时定义这些变量对于以后要更改它们并不是那么有帮助。

p。除非你真的希望将客户端的日期和时间存储在服务器上,否则让服务器提供当前日期总是更好的。时间,从而避免需要从客户端传递它作为突变变量,以及不稳定或恶意值的可能性。

最新更新