简体   繁体   中英

useEffect hook infinite loop

I am new to react. here is my problem

import React, { useEffect, useState } from "react";
import { useJwt } from "react-jwt";
import { get_single_user_url } from "../../store/api";
import UrlCard from "../UrlCard/UrlCard";
import "./Urls.css";

function Urls() {
  const [urls, setUrls] = useState([]);
  const { decodedToken } = useJwt(localStorage.token);
  const userId = decodedToken !== null ? decodedToken.userId : "";

  useEffect(() => {
    const hit = async (userId) => {
      get_single_user_url(userId).then((data) => setUrls(data));
      const data = await get_single_user_url(userId);
      setUrls(data);
      console.log(data);
    };
    hit(userId);
  }, []);

  return <div className="urls"></div>;
}

export default Urls;

so this useeffect will call a function

get_single_user_data(userId)

and it should return an array of urls from the database. But it returned this

{kind: "ObjectId", path: "user", reason: {}, stringValue: """", value: "", proto : Object}

This is the function

export const get_single_user_url = async (userId) => {
  try {
    const response = await axios({
      method: "post",
      url: "http://192.168.43.62:5000/getUrls",
      data: { user: userId },
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });
    console.log(response.data);
    return response.data;
  } catch (error) {
    console.log(error.message);
  }
};

here userId is passed through the body. Now in the backend when I print the value of req.body , it gives user property with an empty string.

{ user: "" }

I have tried it without using useEffect but then it goes into an infinite loop.

Since you have an empty dependency array on your useEffect , it will only fire once. It looks like the userId is an empty string when running.

You'll want to add some logic in your hit function to only make the request if userId is not empty. Additionally, to get your effect to run when needed, you should add userId to the dependency array ( [userId] ).

If userId isn't needed anywhere other than this function, you might use the token instead, and parse the userId in your hit function.

const [urls, setUrls] = useState([]);
const { decodedToken } = useJwt(localStorage.token);

useEffect(() => {
  const hit = async (decodedToken) => {
    const userId = decodedToken !== null ? decodedToken.userId : "";
    if (!userId) {
      return;
    }
    
    get_single_user_url(userId).then((data) => setUrls(data));
    const data = await get_single_user_url(userId);
    setUrls(data);
    console.log(data);
  };

  hit(decodedToken);
}, [decodedToken]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM