skip to Main Content

Description:
Whenever I switch from using localhost as my API endpoint to my actual backend live URL, I encounter two errors in my React application. Here are the errors I’m facing:

PATCH https://hobby-hunter-api.onrender.com/users/6488a0ab682e930dcd661111/64628638beaa4cc4aecd3a42 404 (Not Found) in Friend.jsx:25

`Uncaught TypeError: friends.find is not a function in Friend.jsx:22

I am using MongoDB and Node.js for the backend.
appreciate any insights or solutions to resolve this issue. Thank you!

Additional details:
Please let me know if there’s any additional information or code snippets needed to help diagnose the problem.

Friend component code:

    import { PersonAddOutlined, PersonRemoveOutlined } from "@mui/icons-material";
import { Box, IconButton } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setFriends } from "state";

import UserImage from "./UserImage";

const Friend = ({ friendId, name, userPicturePath }) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { _id } = useSelector((state) => state.user);
  const token = useSelector((state) => state.token);
  const friends = useSelector((state) => state.user.friends);

  const isFriend = friends && friends.find((friend) => friend._id === friendId); // Check if the friend exists

  const patchFriend = async () => {
    const response = await fetch(
      `https://weblinkbackendapi.onrender.com/users/${_id}/${friendId}`,
      {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      }
    );
    const data = await response.json();
    dispatch(setFriends({ friends: data }));
  };

  if (!Array.isArray(friends)) {
    return null; // Return null if friends is not an array
  }

  return (
    <Box className="text-black flex mb-2 bg-zinc-200 justify-between items-center rounded-lg z-10 ease-in duration-500">
      <Box className="flex justify-between items-center gap-1">
        <UserImage image={userPicturePath} />
        <Box
          onClick={() => {
            navigate(`/profile/${friendId}`);
            navigate(0);
          }}
        >
          <h2 className="text-black font-medium hover:text-white cursor-pointer p-2 mr-1">
            {name}
          </h2>
        </Box>
      </Box>
      <IconButton
        onClick={() => patchFriend()}
        sx={{ p: "0.05rem", fontSize: "0.25rem" }}
      >
        {isFriend ? (
          <PersonRemoveOutlined sx={{ color: "grey" }} />
        ) : (
          <PersonAddOutlined sx={{ color: "grey" }} />
        )}
      </IconButton>
    </Box>
  );
};

export default Friend;

2

Answers


  1. Chosen as BEST ANSWER

    I ended up adding a conditional render for the patch a friend function for the current user.The problem was happening when the current user requested himself.


  2. There’re some problems with your code:

    1. Your TypeError occurred because friends was not an array as expected. The friends array check must be proceeded before any further actions, so move it up:
    if (!Array.isArray(friends)) {
        return null; // Return null if friends is not an array
    }
    
    const isFriend = friends.find((friend) => friend._id === friendId); // Check if the friend exists
    ...
    
    1. Your PATCH request failed, you need to check if the API is working and handle error in your code. Reading your logic, your fetching request method should be GET, not PATCH.

    2. By any chance, can state.user.friends a single person? If so, you need to handle the case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search