skip to Main Content

What I am doing is to load data from my local storage which I have fetched from https://jsonplaceholder.typicode.com/users. I am trying to create a react application in which I have added multiple users as a friend just like facebook. my friend list is in the file called UserInfo.js which code I have given bellow. then I tried to show friends corresponding to their id by comparing with the id which I tried to find from api call so that this can show me the matching users.
You can find my project here: https://codesandbox.io/s/elastic-dream-mp3is?file=/src/App.js

import React, { useState } from "react";
import "./UserInfo.css";
import { useEffect } from "react";
import fakedata from "../../fakedata";
import { getDatabaseCart } from "../../utilities/databaseManager";

const UserInfo = () => {
  // // using fakedata
  // const [users, setUsers] = useState(fakedata);

  // // declaring state while calling api
  const [users, setUsers] = useState([]);

  // declaring state while loading data from local storage
  const [friends, setFriends] = useState(users);

  // to load data from Api call
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []);

  // to load data from local storage
  useEffect(() => {
    const savedFriends = getDatabaseCart();
    const friendsId = Object.keys(savedFriends);
    const countFriends = friendsId.map((key) => {
      const friend = friends.find((fd) => fd.id == key);
      // console.log(friend);
      return friend;
    });
    setFriends(countFriends);
  }, [friends]);

  // console.log(friends);
  // console.log(users);

  return (
    <div className="userInfo-container">
      <div className="userInfo">
        {friends.map((friend) => (
          <div>
            <h4>Name: {friend.name}</h4>
          </div>
        ))}
      </div>
    </div>
  );
};

export default UserInfo;

I have created fakedata collecting data from jsonplaceholder and tested according to above method and it worked perfectly. but when I tried to load data API call, I got the following error:

  1. the first error indicates that it can not read property of name which I tried to return from local Storage after matching the id with api call.

2.second error denotes which I can’t understand in my case. I have tried abortCall to handle this error. the error gone but my problem still exits. what can I do now????

first error

second error

3

Answers


  1. In the render, Friends return [{0:undefined}]. You are not setting friends correctly.

    Login or Signup to reply.
  2. I make a Class version of your UserInfo component. It works like this.

    import React from "react";
    import { getDatabaseCart } from "../../utilities/databaseManager";
    
    class UserInfo extends React.Component {
      state = {
        users: [],
        friends: []
      }
      
      componentDidMount = () => {
        this.getDataFromServer();
        this.getDateFromLocalStorage();
      }
    
      getDataFromServer = () => {
        fetch("https://jsonplaceholder.typicode.com/users")
        .then((res) => res.json())
        .then((data) => this.setState({users:data}));
      }
    
      getDateFromLocalStorage = () => {
        const savedFriends = getDatabaseCart();
        const friendsId = Object.keys(savedFriends);
        //console.log(friendsId)
        this.setState({friends:friendsId})
      }
    
      render() {
        const {users, friends} = this.state;
       // console.log('users',users, friends);
       // console.log('friends', friends);
    
        return (
          <div className="userInfo-container">
            <div className="userInfo">
              {users.length > 0 && friends.map((friendId) => {
                const friend = users.find(user => user.id === parseInt(friendId));
                return (
                <div>
                  <h4>Name: {friend && friend.name}</h4>
                </div>
              )})}
            </div>
          </div>
        );
    
      }
    }
    
    
    export default UserInfo;
    

    Note you have a promise for the ‘fetch’ so at first render and until users are fetched user = [] empty array. To avoid errors it’s good to check the length of users before try to map friends.
    You can remove the friend check here because if friends array is empty, there is nothing to map.

    return (
      <div>
        <h4>Name: {friend.name}</h4>
      </div>
    )
    

    Now, it should be a list with ul and li.

    Login or Signup to reply.
  3. With hooks:

    import React, { useState } from "react";
    //import "./UserInfo.css";
    import { useEffect } from "react";
    import fakedata from "../../fakedata";
    import { getDatabaseCart } from "../../utilities/databaseManager";
    
    const UserInfo = () => {
      // // using fakedata
      // const [users, setUsers] = useState(fakedata);
    
      // // declaring state while calling api
      const [users, setUsers] = useState([]);
    
      // declaring state while loading data from local storage
      const [friends, setFriends] = useState([]);
    
      // to load data from Api call
      useEffect(() => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then((res) => res.json())
          .then((data) => setUsers(data));
      }, []);
    
      // to load data from local storage
      useEffect(() => {
        const savedFriends = getDatabaseCart();
        const friendsId = Object.keys(savedFriends);
        setFriends(friendsId);
      }, []);
    
      // console.log(friends);
      // console.log(users);
    
      return (
        <div className="userInfo-container">
          <div className="userInfo">
          {users.length > 0 && friends.map((friendId) => {
                const friend = users.find(user => user.id === parseInt(friendId));
                return (
                <div>
                  <h4>Name: {friend && friend.name}</h4>
                </div>
              )})}
          </div>
        </div>
      );
    };
    
    
    export default UserInfo;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search