0

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);
  }
});

Hi all.I try to fill my redux state when i sign up with users infos and it works well when i sign up. But when i refresh page my redux state gets erased. I used redux-persist but it didn't work either. I have searched many websites for solution to fix it but everyone suggest redux-persist but do i have to use a ready-made package ? what is the source of this issue ?

Umut Palabiyik
  • 313
  • 6
  • 16
  • why are you doing this in signup "dispatch(handleExistEmail(false));" – DevLoverUmar Jul 27 '21 at 05:45
  • İf email exist i change `existEmail` state to true.And i show alert message "Email adrees is exist".I removed it after you said but it still doesnt work :) – Umut Palabiyik Jul 27 '21 at 05:57
  • the only code relevant here is how you set up redux persist, please share that – phry Jul 27 '21 at 06:58
  • I edited can u check again :) – Umut Palabiyik Jul 27 '21 at 07:13
  • The default behavior of redux is to clear the store on a page refresh, so like it has been mentioned, you MUST use something like redux-persist to achieve this. Also, you HAVE NOT listed any relevant code showing how you set up redux-persist. – BryanOfEarth Jul 28 '21 at 19:16
  • check how to configure redux persist with redux-toolkit [redux-persist in redux-toolkit](https://stackoverflow.com/questions/63761763/how-to-configure-redux-persist-with-redux-toolkit) – adi Aug 07 '21 at 15:43

0 Answers0