Caution: Potential Unresolved Promise Rejection Detected (ID: 21) - Error: Undefined is not a valid object when trying to evaluate 'res.json'

ERROR Getting an Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json'). Any suggestions on fixing this issue in my code? I've checked the logs for user and loggeduserobj, and they seem to be correct. However, I'm still encountering this error. I also verified the type of loggeduserobj and it shows as an object. Can someone assist me in resolving 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" });
        })
})

Answer №1

To ensure proper chaining of promises, make sure to return a Promise from your first .then() block when using the fetch function in this way:

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!')
      }
    })
}

In addition, it is recommended to use the await keyword within your async function for better readability and smoother flow:

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!')
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with repeated fields in Google protobuf in JavaScript

Consider this scenario: you have a google protobuf message called Customer with a repeated field as shown below. message Customer { repeated int32 items = 1; } What is the procedure for setting the repeated items field in javascript? ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

Using CSS to style in React is throwing an error: "TypeError: Cannot read property 'image' of undefined"

Hi there! I'm fairly new to web development and React, and I could really use some guidance with my current project. I've been working on pulling data from a local file and trying to display it upon click. Everything goes smoothly until I start ...

Converting Hash Routes to Non-Hash Routes With Next.js Router

I recently updated my React application to nextjs. We replaced the HashRouter with the nextjs Router during the migration process. Our goal is to ensure that when someone deep links to our page, the URLs are forwarded to the routes without the # symbol. ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...

How can I retrieve the index of a v-for loop within a function in Vue.js HTML?

How can I splice the array from the fields in HTML Vue JS if the status is true? I also need to pass the index value to a function. Is this possible? The error I am encountering is: Uncaught ReferenceError: index is not defined at Object.success (80 ...

Tips on integrating the createjs library into a ReactJS project

Hey there! I'm currently working on developing a canvas-based app using ReactJS, and I need to integrate the CreateJS library. As a newcomer to ReactJS, I've been struggling to figure out the best approach. I've tried two different methods - ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

What is the method to effectively conduct a testing procedure for JavaScript files that have been exported using

I have a JavaScript file called "sum.js" which contains a simple function: // sum.js function sum(a, b) { return a + b; } export default { sum }; Now I want to write a test for this file using Jest. Here is my "sum.test.js" file in the same folder: // ...

Discovering the identical element within the ajax response

The following section is being targeted: var obj = $(this).parent().find('a'); // $(this) is a <UL> inside a <DIV>, but there can be multiple DIV>ULs on the page After that, I retrieve some HTML using $.ajax(). This HTML corres ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

Omit specific object properties within a foreach loop in jQuery AJAX

Check Out This Fiddle Example I am currently working with a PHP file that returns JSON data for main content along with an additional property for pagination. I am looking for a way to exclude the pagination property when iterating over the data in a fore ...

The horizontal overflow in the HTML code was unsuccessful

I stumbled upon an interesting issue where I applied a div with specific styling: overflow-x: scroll However, the outcome was not as expected. Instead of overflowing, the content simply started on a new line. Here is the source code for reference: & ...

When attempting to execute a script that includes document.write, it will not function as expected

Our web program is utilizing ajax and jquery, specifically Netsuite. I've been attempting to adjust elements on a page using document.ready and window.load methods in order to load an external script onto the page. Regardless of whether I load this ex ...

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

Encountering an issue with a Next.js app where it has become stuck during execution, the command "npm run dev

After successfully creating a simple next.js app and starting it with npm run dev, I encountered an issue when trying to start it for the second time: enter image description here Even after attempting to create a new project, the problem persisted. Inte ...

Having trouble toggling classes with mouseup in Wordpress Underscores theme

While I'm utilizing Underscores as the foundation theme for my website, one aspect that I particularly appreciate is its incorporation of a functional mobile navigation component. However, since my site is essentially single-page, the navigation remai ...

Issue with JQuery executing PHP in Chrome extension

I have been attempting to retrieve the PHP result after using JQuery's post method within the context of a chrome extension. Unfortunately, all I am seeing is the unprocessed PHP code. Below is how I am calling the post method : $.post(chrome.extens ...