WARN Possible Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json')

WARN Possible Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating ‘res.json’) How can I fix this problem in my code? I tried logging user and loggeduserobj both logs correctly but still, this error is coming I also logged the type of loggeduserobj it logs object Can you help me to fix this problem?

const { user } = route.params;

  const [issameuser, setIssameuser] = useState(false)
  const [follow,  SetFollow] = useState(false)

  const isMyProfile = async (otherprofile) => {
    AsyncStorage.getItem('user').then((loggeduser) => {
      const loggeduserobj = JSON.parse(loggeduser)
      if (loggeduserobj.user.username == otherprofile[0].username) {
        setIssameuser(true)
      }
      else {
        setIssameuser(false)
      }
    })
  }
 

  const CheckFollow = async (otherprofile) => {

    AsyncStorage.getItem('user')
      .then(loggeduser => {
        const loggeduserobj = JSON.parse(loggeduser);
        fetch('http://10.0.2.2:3000/checkfollow', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
           followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
          })
        })
      })
      .then(res => res.json())
      .then(data => {
        if (data.message == "User in following list") {
          SetFollow(true)
        }
        else if (data.message == "User not in following list") {
          SetFollow(false)
        }
        else {
          alert('Please Try Again!')
        }

      })

  }

  useEffect(() => {
    isMyProfile(user)
    CheckFollow(user)
  }, [])

Backend:

router.post('/checkfollow', (req, res) => {
    const { followfrom, followto } = req.body;
    console.log(followfrom, followto);
    if (!followfrom || !followto) {
        return res.status(422).json({ error: "Invalid Credentials" });
    }
    User.findOne({ username: followfrom })
        .then(mainuser => {
            if (!mainuser) {
                return res.status(422).json({ error: "Invalid Credentials" });
            }
            else {
                let data = mainuser.following.includes(followto);
                console.log(data);
                if (data == true) {
                    res.status(200).send({
                        message: "User in following list"
                    })
                }
                else {
                    res.status(200).send({
                        message: "User not in following list"
                    })
                }
            }

        })
        .catch(err => {
            return res.status(422).json({ error: "Server Error" });
        })
})

>Solution :

You need to return a Promise, the result of fetch, from your first .then() so that it can be chained on, like so:

const CheckFollow = async (otherprofile) => {
  AsyncStorage.getItem('user')
    .then(loggeduser => {
      const loggeduserobj = JSON.parse(loggeduser);
      return fetch('http://10.0.2.2:3000/checkfollow', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
        })
      })
    })
    .then(res => res.json())
    .then(data => {
      if (data.message == "User in following list") {
        SetFollow(true)
      } else if (data.message == "User not in following list") {
        SetFollow(false)
      } else {
        alert('Please Try Again!')
      }
    })
}

You should also consider using await in this case, especially since your function is already marked as async to make things more readable

const CheckFollow = async (otherprofile) => {
  const loggeduser = await AsyncStorage.getItem('user');
  const loggeduserobj = JSON.parse(loggeduser);

  const res = await fetch('http://10.0.2.2:3000/checkfollow', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      followfrom : loggeduserobj.user.username, followto: otherprofile[0].username
    })
  });

  const data = await res.json();

  if (data.message == "User in following list") {
    SetFollow(true)
  } else if (data.message == "User not in following list") {
    SetFollow(false)
  } else {
    alert('Please Try Again!')
  }
}

Leave a Reply