Home > front end >  Fetching Friends from api and Display on the frontend
Fetching Friends from api and Display on the frontend

Time:11-04

i'M working on a Chat Application project

but im getting this error of fetching friends from the backend(node)

I'm getting the friends data on the console but i'm unable to display it.

this is my Context and States

 export const Messenger = () => {
  // Context State
  const { friends, setFriends, authInfo } = useAuth();
  const [loggedUser, setLoggedUser] = useState();
  const { updateNotification } = useNotification();

  const fetchMessengerUsers = async () => {
    try {
      const token = getToken();
      const config = {
        headers: {
          authorization: "Bearer "   token,
        },
      };
      const { data } = await client("/get-friends", config);
      console.log(data);
      setFriends(data);
    } catch (error) {
      updateNotification("error", "Failed To load the Chat");
    }
  };
  useEffect(() => {
    setLoggedUser(localStorage.getItem("auth-token"));
    fetchMessengerUsers();
  }, []);

then in return i'm mapping all friends to display them

<div className="friends">
          {friends && friends.length > 0
            ? friends.map((fd) => (
                <div className="hover-friend">
                  <Friends friend={fd} />
                </div>
              ))
            : "No Friend"}
        </div>

It displays No Friend on the browser

this link shows how it appears on the browser

CodePudding user response:

just change your fetchMessengerUsers function.

you need to set setFriends(data.friends)

      const fetchMessengerUsers = async () => {
        try {
          const token = getToken();
          const config = {
            headers: {
              authorization: "Bearer "   token,
            },
          };
          const { data } = await client("/get-friends", config);
          console.log(data);

          setFriends(data.friends); // you have to set friends array here, earlier you were setting the entire object.
        } catch (error) {
          updateNotification("error", "Failed To load the Chat");
        }
      };
  • Related