userslice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { API } from "../axios/index";
export const signUp = createAsyncThunk("users/signup", async (params) => {
try {
const { formData, dispatch, history } = params;
const { data } = await API.post("/users/signup", formData);
history.push("/");
dispatch(handleExistEmail(false));
return data;
} catch (error) {
console.log("aha hata var");
const { dispatch } = params;
const { status } = error.response;
if (status) {
dispatch(handleExistEmail(true));
}
}
});
export const logOut = createAsyncThunk("users/logout", async (params) => {
try {
const { id } = params;
const { data } = await API.put(`users/logout/${id}`);
localStorage.removeItem('user')
return data;
} catch (error) {
console.log(error);
}
});
const initialState = {
usersInfo: {},
status: "idle",
error: null,
existEmail: false,
};
const usersSlice = createSlice({
name: "users",
initialState,
reducers: {
handleExistEmail: (state, action) => {
state.existEmail = action.payload;
},
},
extraReducers: {
[signUp.pending]: (state, action) => {
state.status = "loading";
},
[signUp.fulfilled]: (state, action) => {
state.status = "succeeded";
state.usersInfo = action.payload;
localStorage.setItem("user", JSON.stringify(action.payload));
},
[signUp.error]: (state, action) => {
state.status = "failed";
state.error = "error";
},
},
});
export default usersSlice.reducer;
export const { handleExistEmail } = usersSlice.actions;
auth.jsx
import React, { useState } from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
import { signUp } from "../features/usersSlice";
import { useDispatch, useSelector } from "react-redux";
import Message from "../components/Message";
const AuthScreen = ({ history }) => {
const existEmail = useSelector((state) => state.users.existEmail);
const dispatch = useDispatch();
const [login, setLogin] = useState(true);
const [formData, setFormData] = useState({
email: "",
password: "",
confirmPassword: "",
firstName: "",
lastName: "",
});
const handleSignUp = (e) => {
console.log("kayıt olma işlemi çalıştı")
if (formData.password === formData.confirmPassword) {
e.preventDefault();
dispatch(signUp({ formData, dispatch, history }));
} else {
e.preventDefault();
}
};
return (
<>
<Container>...
</>
);
};
export default AuthScreen;
userrouter.js
import express from "express";
import User from "../models/userModel.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import tokenModel from "../models/tokenModel.js";
const router = express.Router();
router.post("/signup", async (req, res) => {
try {
const { email, password, confirmPassword, firstName, lastName } = req.body;
const userExists = await User.findOne({ email });
if (userExists) {
console.log("A user with this email already exists");
return res
.status(400)
.json({ message: "A user with this email already exists" });
}
if (password !== confirmPassword) {
return res.status(400).json({ message: "Passwords don't match" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({
email,
name: `${firstName} ${lastName}`,
password: hashedPassword,
});
const accessToken = jwt.sign(
{ email: user.email, id: user._id },
process.env.ACCESS_TOKEN_SECRET,
{
expiresIn: "3m",
}
);
const refreshToken = jwt.sign(
{ email: user.email, id: user._id },
process.env.REFRESH_TOKEN
);
await tokenModel.create({
userId: user._id,
refreshToken: refreshToken,
});
res.status(200).json({ user, accessToken });
} catch (error) {
console.log(error);
}
});
大家好。当我注册用户信息时,我尝试填充我的redux状态,注册时效果很好。但当我刷新页面时,我的redux状态被删除。我使用了redux,但它也不起作用。我已经在很多网站上搜索解决方案来修复它,但每个人都建议继续使用redux,但我必须使用现成的软件包吗?这个问题的根源是什么?
暂无答案!
目前还没有任何答案,快来回答吧!