身份验证值在页面刷新后为空- React

huangapple go评论90阅读模式
英文:

Auth value is null after page refresh- React

问题

It seems like you're encountering an issue where the auth.id becomes null when you refresh the page. This could be due to how you are handling authentication and storing the user ID in your application. Here are some steps to help you debug and potentially fix the issue:

  1. Check Local Storage: Verify that the user ID is correctly stored in local storage when the user logs in. You can use browser developer tools to inspect the local storage and ensure that the userId item is being set correctly.

  2. Retrieve User ID on Page Load: In your AuthContext component, you are retrieving the user ID from local storage during the useEffect hook. Ensure that this code correctly fetches and sets the user ID.

  3. Context Provider Placement: Make sure that the AuthProvider component wraps your entire application or at least the components where you need access to the auth context. It should be placed higher up in your component hierarchy to provide consistent authentication data throughout your app.

  4. Check Dependencies in useEffect: In your Exercises component, you have a useEffect that depends on auth.id. Ensure that this dependency is correctly set and that it's not inadvertently being reset to null elsewhere in your code.

  5. Debugging: Use console.log statements to track the value of auth.id at different points in your application's lifecycle. This can help you identify where and why it's being set to null.

  6. Error Handling: If you're using any third-party libraries for authentication, check their documentation and error handling to ensure that you're handling authentication-related issues correctly.

  7. CORS and Network Requests: Ensure that there are no cross-origin resource sharing (CORS) issues affecting your network requests. CORS issues can sometimes lead to unexpected behavior in your application.

By following these steps and carefully inspecting your authentication and state management code, you should be able to pinpoint the issue and work towards a solution. If you continue to face problems, providing more specific details about where auth is defined and how it's used throughout your application would be helpful for further assistance.

英文:

I am developing an application and this is my code in react:

import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import styles from "./ExercisePage.module.css";
import api from "../../apis/requestService";
import useAuth from "../../hooks/useAuth";

function Exercises() {
  const { setAuth, auth, loading } = useAuth();
  const { id } = useParams();
  const navigate = useNavigate();
  const [requests, setRequests] = useState([]);
  const [exerciseData, setExerciseData] = useState({
    weight: "",
    reps: "",
    exerciseId: id,
    date: null,
  });
  const [err, setErr] = useState("");
  const [popupStyle, showPopup] = useState("hide");

  const { weight, reps } = exerciseData;
  useEffect(() => {
    setExerciseData((prevData) => ({
      ...prevData,

      exerciseId: id,
      date: new Date(),
    }));

    api.getUserExercises(id).then((response) => {
      setRequests(response.data);
    });
  }, [id, auth.id]);

  const onInputChange = (e) => {
    setExerciseData({ ...exerciseData, [e.target.name]: e.target.value });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    console.log("User id" + auth.id);
    const updatedExerciseData = {
      ...exerciseData,
      userId: auth.id,
      date: new Date(),
    };

    api
      .createRequest(updatedExerciseData)
      .then((response) => {
        if (response.data.id) {
          return api.getUserExercises(auth.id);
        } else {
          throw new Error("An error occurred while creating the request.");
        }
      })
      .then((response) => {
        setRequests(response.data);
        setExerciseData({ ...updatedExerciseData, weight: "", reps: "" });
      })
      .catch((error) => {
        console.error(error);
        setErr("An error occurred while creating the request.");
      });
  };

  const popup = () => {
    showPopup("exercise-popup");
    setTimeout(() => showPopup("hide"), 3000);
  };

  return (
    <div className={styles.wrapper}>
      <div className={styles.content}>
        {requests.length > 0 ? (
          requests.map((request, index) => (
            <div key={index} className={styles.requestBox}>
              <div className={styles.requestDetails}>
                <h2>{request.exercise.name}</h2>
                <p>{request.exercise.description}</p>
              </div>
              <img
                src={request.exercise.imageUrl}
                alt={request.exercise.name}
              />
              <div className={styles.requestInfo}>
                <p>Weight: {request.weight} kg</p>
                <p>Reps: {request.reps}</p>
                <p>Date: {new Date(request.date).toLocaleDateString()}</p>
              </div>
            </div>
          ))
        ) : (
          <p>No exercises assigned yet.</p>
        )}
      </div>
      <form onSubmit={(e) => onSubmit(e)} className={styles.exerciseForm}>
        <h1 className={styles.h1Text}>
          Set <br /> Exercise
        </h1>
        <div className={styles.inputContainer}>
          <label htmlFor="weight" className={styles.inputLabel}>
            Enter weight
          </label>
          <input
            id="weight"
            name="weight"
            type="number"
            value={weight}
            min="0"
            onChange={onInputChange}
            className={styles.inputBox}
          />
        </div>
        <div className={styles.inputContainer}>
          <label htmlFor="reps" className={styles.inputLabel}>
            Enter reps
          </label>
          <input
            id="reps"
            name="reps"
            type="number"
            value={reps}
            min="0"
            onChange={onInputChange}
            className={styles.inputBox}
          />
        </div>
        <button className={styles.exerciseBtn} type="submit">
          +
        </button>
        <div className={popupStyle}>
          <h3>{err}</h3>
        </div>
      </form>
    </div>
  );
}

export default Exercises;

When I refresh the page the id from auth is null. When I innitialy enter the page the id is fine but when I refresh it is set to null. This is the auth code:

// import { createContext, useState, useEffect } from "react";

// const AuthContext = createContext({});

// export const AuthProvider = ({ children }) => {
//   const [auth, setAuth] = useState({});
//   const [loading, setLoading] = useState(true);

//   useEffect(() => {
//     const storedToken = localStorage.getItem("accessToken");
//     const storedRoles = localStorage.getItem("roles");
//     const storedId = localStorage.getItem("userId");

//     if (storedToken && storedRoles) {
//       const token = JSON.parse(storedToken);
//       const roles = JSON.parse(storedRoles);
//       const id = JSON.parse(storedId);
//       setAuth({ token: token, roles: roles, id: id });
//     }
//     setLoading(false);
//   }, []);

//   const logout = () => {
//     // Clear the auth state
//     setAuth({});
//     // Remove the user data from local storage
//     localStorage.removeItem("accessToken");
//     localStorage.removeItem("roles");
//     localStorage.removeItem("userId");
//   };

//   return (
//     <AuthContext.Provider value={{ auth, setAuth, loading, logout }}>
//       {children}
//     </AuthContext.Provider>
//   );
// };

// export default AuthContext;
import { createContext, useState, useEffect } from "react";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const storedToken = localStorage.getItem("accessToken");
    const storedRoles = localStorage.getItem("roles");
    const storedId = localStorage.getItem("userId");

    if (storedToken && storedRoles) {
      const token = JSON.parse(storedToken);
      const roles = JSON.parse(storedRoles);
      const id = JSON.parse(storedId);
      setAuth({ token: token, roles: roles, id: id });
    }
    setLoading(false);
  }, []);

  return (
    <AuthContext.Provider value={{ auth, setAuth, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;

What is my mistake. Please help. I have no idea what to do or from where to start from.

答案1

得分: 1

Your code won't run as expected, Here's why:

当您初始化一个自定义Hook(useAuth)时,您将auth对象的初始值设置为'{}'。所以无论您之前保存了什么到这个状态/上下文中,它都会被重置。

唯一会保留的是来自useParameter()的id

如果您想保持数据的持久性,我建议使用localStorage API。

另外,您可以阅读这个链接,了解如何在刷新后保持数据的持久性2

英文:

Your code won't run as expected, Here's why:

When you are initiating a customHook (useAuth) you set an initial value of '{}' to auth object. So no matter what you saved before to this state/context. It will reset.

> The only thing that will persist is the id from useParameter()

If you wanna keep your data persistent I recommend using localStorage API.

Also you can read this link on how to keep your data persistence even after refresh.

huangapple
  • 本文由 发表于 2023年5月14日 08:21:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定