提问人:deadant88 提问时间:11/7/2023 更新时间:11/7/2023 访问量:26
使用 redux 工具包调度的竞争条件
Race condition using redux toolkit dispatch
问:
我正在尝试根据登录用户是否已完成载入有条件地导航。在下面的函数中,逻辑似乎没有等待调度足够长的时间(或根本没有等待),从而导致导致并触发错误的条件导航逻辑的争用条件。currentStudent.onboardingCompleted
undefined
我想知道如何更好地构建事物以使其更稳定?
const StudentLoginForm = () => {
const [spellcastUsername, setSpellcastUsername] = useState('');
const navigate = useNavigate();
const dispatch = useDispatch<AppDispatch>();
const [isLoading, setIsLoading] = useState(false);
const currentStudent = useSelector(
(state: RootState) => state.selectedStudent,
);
const handleSubmit = async (spellcastUsername: string) => {
setIsLoading(true); // Start loading
try {
const isStudentAuthenticated = await api.dbAuthenticateStudent(
spellcastUsername,
);
if (isStudentAuthenticated) {
preloadPhonemeAudio();
await dispatch(
fetchStudentAndCreateSessionThunk(isStudentAuthenticated.id),
);
if (currentStudent?.onboardingCompleted === true) {
navigate(`/cardgame/${isStudentAuthenticated.id}`);
} else {
navigate(`/profile/${isStudentAuthenticated.id}`);
}
} else {
alert('No User');
}
} catch (error) {
console.error('Error during form submission:', error);
alert('An error occurred. Please try again.');
} finally {
setIsLoading(false);
}
};
[...]
这是砰的一声:
export const fetchStudentAndCreateSessionThunk = createAsyncThunk(
'session/fetchAndCreate',
async (studentId: string, { dispatch, getState }) => {
await dispatch(fetchStudentByIdThunk(studentId));
const state = getState() as RootState;
const studentNode = state.selectedStudent;
if (studentNode && studentNode.id) {
dispatch(setSelectedStudent(studentNode));
dispatch(createNewSessionThunk(studentNode.id));
}
},
);
我
答: 暂无答案
评论