页面刷新后 redux 状态被擦除(redux-toolkit)

时间:2021-07-27 05:38:27

标签: javascript reactjs redux-toolkit redux-persist

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-persist 但它也不起作用。我在很多网站上搜索了解决方案来修复它,但每个人都建议使用 redux-persist 但我必须使用现成的包吗?这个问题的根源是什么?

0 个答案:

没有答案