Post Data with Nested Objects Using Axios

I am facing an issue where I want to store multiple options in an array named options from a form that contains textboxes. However, instead of each option being added under the parameter options, they are getting overridden by one another.

hooks

  const [description, setDescription] = useState("");
  const [text, setText] = useState("");
  const [type, setType] = useState("");
  const [options, setOptions] = useState([]);

submit function

    e.preventDefault();
    axios({
      method: "post",
      url: "http://localhost:8080/new/",
      data: {
      
        title: title,
        description: description,
      
      questions:{
         text: text,
        type: type,
        options: options,
      } 
      
      },
      config: { headers: { "Content-Type": "application/json" } },
    })
      .then(function () {
        alert("Successfully submitted application.");
      })
      .catch(function (error) {
        alert("Failed to submit application.");
        console.log(error);
      });
  }

Options Section in form

 <input
            required
            type="options"
            id="options"
            name="options"
            value={options}
            onChange={(e) => setOptions(e.target.value)}
            placeholder="ex. A).Blue"
          />
          <br />
          B:&nbsp;&nbsp;
          <input
            required
            type="options"
            id="options"
            name="options"
            value={options}
            onChange={(e) => setOptions(e.target.value)}
            placeholder="ex. B).Red"
          />
          <br />

Submit button

          variant="primary"
          onClick={(e) => {
            SubmitQuiz(e);
          }}
          type="submit"
        >
          Submit Quiz
        </button>

output

title   "I"
description "need"
questions   
text    "some"
type    "Select One"
options "help"

desired output https://i.sstatic.net/CqRHi.jpg

Answer №1

Generate multiple input fields using map, and assign a name to each input as follows:

i = 0;

name=`options.${i}`

Make sure to increment the i variable for each input field.

For instance, in your implementation:

<input
    required
    type="options"
    id="options"
    name="options.0"
    value={options}
    onChange={(e) => setOptions(e.target.value)}
    placeholder="ex. A).Blue"
 />
 <br />
 B:&nbsp;&nbsp;
 <input
     required
     type="options"
     id="options"
     name="options.1"
     value={options}
     onChange={(e) => setOptions(e.target.value)}
     placeholder="ex. B).Red"
 />
 <br />

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

PhantomJS encountered a TypeError when trying to access a non-existent object during the evaluation of 'document.getElementById()'

Recently, I delved into the world of PhantomJS and its ability to extract data from websites through JavaScript. This process is commonly referred to as web scraping. My goal was to retrieve the text content of an element by its ID. However, I encountered ...

Dynamic routing with Backbone is causing issues with loading static files

I am facing a challenge with setting up dynamic routing in Backbone. I have configured an Express application that serves a Backbone Single Page Application (SPA). My route setup is as follows: var AppRouter = Backbone.Router.extend({ routes: { ... ...

Issue with adding events using .on() to dynamically added items in datatables when using ajax based fnDraw()

Whenever the checkbox is selected, a datatable retrieves fresh data using ajax and fnDraw(). Unfortunately, the .on() event is failing to add the event properly. $("#reviewcheck").click(function() { reviewTable.fnDraw(); }); $(".review tbody td img").o ...

Issue encountered while trying to access PHP script within table data utilizing Ajax

I have a small project that involves displaying different news articles. I need to incorporate the news_all.php file into the table data in dashboard.php without using the include('news.php) function. Instead, I am utilizing Ajax methods to achieve th ...

The forked library fails to generate a dist folder within the node-modules directory

Having an issue with a Vue.js plugin from GitHub. Here's the link: https://github.com/antoniandre/vue-cal I forked it and made some changes, but when I try to install the node_modules folder, the dist folder is missing. Any idea what could be causing ...

What steps can I take to maximize the efficiency of my code for optimal performance?

I am working on speeding up my code for improved performance. The snippet below is a part of the code responsible for extracting data from a website, identifying specific values, and then displaying them using console.log. My objective is to optimize this ...

The GET method is unable to process the body

I have been utilizing mockoon for creating API simulations. I set up 2 routes with the GET method, each responding with a JSON object. Interestingly, my express app seems to struggle parsing one of the routes. However, the route that includes an array in t ...

The breakdown of an object literal in JavaScript

What is the reason that we cannot access the second item in the object literal the same way as the first? var foo = {a:"alpha",2:"beta"}; console.log(foo.a) -> printing 'alpha' correctly console.log(foo.2) -> Error: missing ) after argumen ...

How can I dynamically access the value of theme.mixins.toolbar.minHeight in MUI?

How can I effectively utilize MUI's theme.mixins.toolbar to calculate the height using height: calc(100vh - toolbar)? I am currently experimenting with this approach: function SwipeCard() { return ( <Box sx={{ height: (theme) = ...

jQuery's AJAX functionality may not always register a successful response

Below is the code snippet I am currently working with: $(".likeBack").on("click", function(){ var user = $(this).attr("user"); var theLikeBack = $(this).closest(".name-area").find(".theLikeBack"); $.a ...

What is the purpose of calling Array.prototype.slice on an array with 0 as the starting index?

While exploring the inner workings of Sizzle, I stumbled upon this particular line of code: array = Array.prototype.slice.call( array, 0 ); Upon researching the function, it seems like all it does is return every element in the array starting from index ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

How to leverage the parent component scope within the b-table slot

I am working with a v-slot in a <b-table> to create a link. The link's initial part consists of data from the source. However, there is a parameter in the querystring that I need to include in the link. How can I access the scope of my data con ...

I encountered an issue after updating data with ajax where a property in a bootstrap button went missing, causing a modal to malfunction

Currently, I am working on a project using Django and for handling Ajax calls, I have been referring to this project: https://pypi.org/project/django-bootstrap-modal-forms/ In my project, there is a table where by clicking the Ver Tratamiento button, I ca ...

Navigating through JavaScript list items

When I send an API request, the response I get looks something like this: //Sample Response [ { "id": 34, "user_id": 1, "first_name": "Awesome", "last_name": "Person", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Calculate the total sum of all numerical values within an array of objects

Here's an example of an array: const arr = [{ a: 12, b: "A" c: 17 }, { a: 12, b: "B" c: 17 }, { a: 12, b: "C" c: 17 } ]; What is the most efficient way to calculate the sum of all objects in the array? T ...

The term 'TextInput' is not recognized in React Native and cannot be found

I'm currently working on setting up a login screen for a social media app that I am developing. The issue I am facing is that I have a LoginScreen.js and RegisterScreen.js with forms for email and password, but when I try to render them, I encounter a ...

Merge HTML documents with this powerful JavaScript library

Our team has developed an email generator that creates HTML emails based on specific parameters. Users can simply select or deselect options and the email will be regenerated accordingly. Occasionally, users may need to make minor manual changes to the co ...

Tips for maintaining data in a React component across re-renders?

Currently, I am working on creating a basic axios call to communicate with a nodejs server from a react application in order to retrieve products stored in a mongoose schema model. The issue I am facing is that when the page initially loads, I can successf ...

What is the best way to evaluate two objects with varying data types?

Is it possible to compare two objects with different data types? var a = { sort: 7, start: "0"} var b = { sort: "7", start: "0"} I thought they should be equal, but when I try using JSON.stringify(a) === JSON.stringify(b), it returns false. ...