Linking the Front End and Back End through Mongodb in a MERN Stack

I am currently working on connecting the front-end sign-in page to the backend MongoDB. However, I am encountering an error which is mentioned below. This piece of code retrieves data from the front end and sends it to the backend for registration.

    name: "",
    email: "",
  });

  let name, value;
  const handleInputs = (e) => {
    console.log(e);
    name = e.target.name;
    value = e.target.value;

    setuser({ ...user, [name]: value });
  };

  const PostData = async (e) => {
    e.preventDefault();
    // http://localhost:3002/register
    const [name, email] = user;
    console.log(name);
    console.log(email);
    const res = await fetch("/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name,
        email,
      }),
    });
    const data = await res.json();
    console.log(name);
    console.log(email);
    if (data.status === 422 || !data) {
      window.alert("Invalid Registration");
    } else {
      window.alert("Registration Successful");
    }
  }; 

Error messages:

Uncaught (in promise) TypeError: user is not iterable at PostData (App.js:30:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) at invokeGuardedCallback (react-dom.development.js:4277:1) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1) at executeDispatch (react-dom.development.js:9041:1) at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)

at processDispatchQueue (react-dom.development.js:9086:1) at dispatchEventsForPlugins (react-dom.development.js:9097:1) at react-dom.development.js:9288:1

Answer №1

It appears there may be an issue with the user object. To troubleshoot, consider logging it to see its value at each step. You can also try using JSON.parse(). Additionally, instead of passing name and email to JSON.stringify(), try a different approach like destructuring the user object using const {name, email} = user rather than const [name, email] = user;

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

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

I can't see the presence of spin.js on my website

I am completely new to Javascript and I'm trying to implement a loading spinner on my website. Whenever users tap the screen, it takes some time to navigate to the desired URL, so we need a spinner to prevent them from tapping repeatedly. I decided t ...

What is the best way to setup a function parameter to store responses from an inquirer.prompt inquiry using JavaScript and integrating with MySQL?

How can I incorporate function parameters to handle answers from an inquirer.prompt question in JavaScript? While I already know how to achieve this without using variables, I aim to enhance the usability of my addToTable function by utilizing parameters ...

Switch between using a dropdownlist and textbox depending on the selection in another dropdownlist

In the process of developing an application, I have implemented a country dropdown list and a state dropdown list. Here's the scenario: when a user selects a country, the states for that country will populate in the state dropdown list. However, the ...

Waiting for a response is not the same as waiting for firebase batches functions

There's a simple function that sets the loader value to true and then, when the function finishes, it sets it back to false. However, I'm facing an issue where my async/await functions are not properly awaiting the code that involves firebase bat ...

I am utilizing Google OAuth for authentication. Is there a way to retrieve the user's information?

I am currently using Google Passport for authentication, but now I need to access additional user details like profile image and gender. Can anyone guide me on how to retrieve this information? Your assistance would be greatly appreciated. exports.googleP ...

Should URL parameters be avoided as a method for retrieving data with React Router in a React application?

Within my application, there exists a main page labeled Home that contains a subpage named Posts. The routing structure is as follows: <Route path='/' element={<Home />} /> <Route path='/posts/popular' element={<Post ...

Using <span> tags to wrap sentences within <p> tags while maintaining the rest of the HTML formatting

In order to achieve my goal, I have utilized the following code to extract content within tags and encapsulate each sentence in tags for easier interaction. $('p').each(function() { var sentences = $(this) .text() ...

Setting dropdown options dynamically within an ng-repeat loop

I am currently encountering an issue with my Angular code, particularly when populating the dropdown within an HTML table (Code provided below). Could someone kindly assist me in determining what actions need to be taken inside modify() in order to populat ...

Correct the string based on a character error

When I have text to display in HTML, for example: var htmlStr = "1.first thing %10-15%. 2.second thing %25-44%. 3.third" And I want to display it in a div: $('#div1').html(htmlStr); However, when I display it in a DIV1 in HTML5 on a mobile pho ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

Expanding the size of a JavaScript array by adding fields

I have extended the JS array prototype by adding a "max" field. However, I am encountering difficulties in displaying this addition when stringifying the array. Despite attempting to modify the toJSON function, my efforts have been unsuccessful. Array.pro ...

How can the parameters for a cube geometry in three.js be dynamically updated?

Wondering about something here. I noticed that Three.js geometries come with 'parameter' fields associated with them. Take, for example, the box geometry shown in the image below... box Geometry parameters I attempted to update these parameters ...

Passing a socket from a Node socket.io server to another file

When developing my app, I have a main file named app.js and another file called Rooms.js where I handle all functions related to socket.io rooms. In app.js, I import the module like this: var Rooms = require("./methods/Rooms") Rooms.Rooms(io, socket); I ...

How can nested fields be utilized to establish a many-to-many relationship in MongoDB/Mongoose?

Working on understanding how to establish a many-to-many relationship in mongodb/mongoose. I have created two Schemas: // User Schema var UserSchema = mongoose.Schema({ email: { type: String, index:true }, name: { type ...

Utilize Node.js to gather information from various websites

I want to create a program that can download data from various websites like WHO, UNICEF, Eurostat, etc. and then convert this data into JSON format. This process is known as web scraping, right? The data may be in different formats such as html, PDF, xls ...

What is the best way to save cache in a web browser?

Is it possible to store data in the browser's cache and have it persist even after closing the browser, so that when I return to my application the cached data is still there? If this is possible, how can it be achieved? ...

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...

Locate unaccented data to uncover accented words using Node.js and MongoDB

I am currently working on a translator MERN stack app where in the database I have the word "föderativ". The user is only able to search for this word using the accented ö letter. However, I want users to be able to simply type "foderativ" and still matc ...

What sets this.prototype apart from module.exports?

As a newcomer to the world of Node.js, I am eager to gather information, experiment with testing techniques, and explore the code written by others. In my exploration, I have noticed that creating and requiring modules is a common practice in Node.js. Dif ...