Back

Why i am ended up getting infinte loop is there any way to restrict it

  • 0
  • Functions
  • Web
kusal
23 Aug, 2024, 17:58
TypeScript
TL;DR
Developers are dealing with an infinite loop issue in a React component where the useEffect hook is triggering a state change. The problem arises due to the dependency array in the useEffect hook. To solve this, developers should remove 'owner' from the dependency array.
kusal
23 Aug, 2024, 17:59
TypeScript

const Thread = ({ thread, setthraeds, onuserdata }) => {
  const [loading, setloading] = useState(true);
  const [owner, setowner] = useState(null);
  const [threadinstances, setthreadinstace] = useState(thread);

  const handledelete = async (e) => {
    e.preventDefault();
    await database.deleteDocument(VITE_DBID, VITE_COLLECTIONID, thread.$id);
    setthraeds(prevstate => prevstate.filter(item => item.$id !== thread.$id));
  };

  let createdate = thread.$createdAt;

  useEffect(() => {
    const fetchUserData = async () => {
      const payload = { 'owner_id': thread.owner_id };
      try {
        const response = await functions.createExecution('65e6b4bd0baa96e174fc', JSON.stringify(payload));
        const profile = await database.getDocument(VITE_DBID, VITE_COLLECTIONID_USERPROF, thread.owner_id);
        const userdata = JSON.parse(response.responseBody);
        userdata.Profile_pic = profile.Profile_pic;
        setowner(userdata);
        onuserdata(userdata);
        setloading(false);
      } catch (error) {
        console.log(error);
      }
    };

    fetchUserData();
  }, [owner, functions, database, VITE_DBID, VITE_COLLECTIONID_USERPROF, onuserdata]);

  const toggleLike = async () => {
    const user_who_like = thread.user_who_like;
    const currentuserid = thread.owner_id;

    if (user_who_like.includes(currentuserid)) {
      const index = user_who_like.indexOf(currentuserid);
      user_who_like.splice(index, 1);
    } else {
      user_who_like.push(currentuserid);
    }

    const payload = {
      'user_who_like': user_who_like,
      'likes': user_who_like.length
    };

    const response = await database.updateDocument(VITE_DBID, VITE_COLLECTIONID, thread.$id, payload);
    setthreadinstace(response);
  };

  if (loading) return null;

  return (
 

export default Thread;
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more