Tips for updating the value of a key in a JavaScript object when the TextField tag's value changes

Here is the schema I am using for my model:

const workoutSchema = mongoose.Schema({
  workouts: [
    {
      workoutName: String,
      sets: Number,
      reps: Number,
      weight: Number,
    },
  ],
});

Below is the postData referenced in the text field.

const [postData, setPostData] = useState({
    workouts: [{ workoutName: "", sets: "", reps: "", weight: "" }],
  });

In order to access the workoutName mentioned above, I have set the value to

postData.workouts["workoutName"]
, which seems to work but I'm not entirely certain. My issue lies with the onChange property, particularly with the second argument in setPostData [workoutName]: e.target.value. I am struggling to access the workoutName key within the workouts dictionary from the schema.

<TextField
              label="Workout"
              variant="outlined"
              value={postData.workouts["workoutName"]}
              onChange={(e) =>
                setPostData({ ...postData, workoutName: e.target.value })
              }

I have attempted

workouts["workoutName"]: e.target.value
, but it results in a syntax error before the bracket, indicating that a comma was expected. See the error image. Additionally, I tried
workouts.workoutName : e.target.value
, as in other programming languages, but it did not work. How can I properly access the workoutName within the workouts object to update it with the value typed in the text field (i.e., e.target.value)?

Answer №1

postData is a data object

Within this data object, there is a key called "workouts"

Inside the array of "workouts", each item has a property named "workout name"

To update the workout name, you can use the following code:

{...postData, workouts: [{...postData.workouts[0], workoutName: e.target.value}]}

To retrieve the workout name, you should do the following:

postData.workouts[0].name

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

Send a single piece of data using AJAX in Flask

I have a very basic HTML form containing only one <input type='text'> field for entering an email address. I am trying to send this value back to a Python script using AJAX, but I am having trouble receiving it on the other end. Is there a ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...

Create a parent dropdown class that contains two separate bootstrap dropdowns nested within it

I am encountering an issue with my dropdown menus. I have 2 dropdown menu items under the same parent dropdown class. However, when I click on dropdown action 1, it displays the body of dropdown menu 2 items instead. <!DOCTYPE html> <html> < ...

Display all keys and values in a dynamically populated object on my screen - React

I have a dynamic object with nested objects, and I want to display every key and value. Even if there are objects within the main object, I need to show their keys and values as well. Here is an example of the object: info:{ address:{ city: {__o ...

When implementing v-model on a v-dialog component, it causes the element within an array to

There is an array of apps with links, and a Dialog component that has v-model="dialog" to close it. However, after adding v-model to the v-dialog, the functionality of the apps is affected. The current app is passed as a prop to Dialog, but it always sends ...

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

When attempting to add an object to an array in a collection, there was an issue with

In my application, I am accessing a collection in Mongodb using ReactJS and mongoose. One of the properties in this collection is set to an Array type. When I add elements to this Array, they are successfully added but for some reason, the _id field that ...

Why does my Javascript cross-domain web request keep failing with a Status=0 error code?

UPDATE: I've been informed that this method doesn't work because craigslist doesn't have an Allow-Cross-Domain header set. Fair point. Is there an alternative way to download a page cross-domain using Javascript in Firefox? It's worth ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Exploring creative methods for incorporating images in checkboxes with CSS or potentially JavaScript

Although it may seem like a basic question, I have never encountered this particular task before. My designer is requesting something similar to this design for checkboxes (positioned on the left side with grey for checked boxes and white for unchecked). ...

Is it possible for multiple queries executed within a websql transaction to be run concurrently?

An informative tutorial online demonstrates the following transaction: db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")&ap ...

What steps can I take to safeguard my Javascript from unauthorized access by external entities?

Basically, I have a website with a Javascript library that has ads integrated through a script tag. My main concern is whether these ads can access my Javascript library, which makes Ajax calls to a server where the user is logged in. I want to protect my ...

Repurposing Styles in JavaScript

I recently started using Material UI and I've noticed that I'm repeating a lot of CSS styles. In the past, I would use a global style sheet to reuse classes, but I'm not sure how to do that with this framework. After going through the docum ...

Choosing options from Bootstrap dropdown using Protractor

I am working with a Bootstrap single-button dropdown and I need to programmatically click on one of the options in the dropdown using Protractor. How can I achieve this? <div class="btn-group" ng-if="!persist.edit" dropdown> ...

Text element in SVG not displaying title tooltip

Looking for a solution to display a tooltip when hovering over an SVG Text element? Many sources suggest adding a Title element as the first child of the SVG element. This approach seems to work in Chrome, but not in Safari - the primary browser used by mo ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

Picked (chosen-js): Steps to deselect options using a variety of selectors

I am currently using the Chosen library on Vue and Webpack for my project. I have a scenario where I need to cancel a selection when multiple options are selected, but I am struggling to achieve this. Can anyone guide me on how to cancel a selected optio ...

Having trouble with the express-stormpath login feature for users who have authenticated with their email?

As I run a basic node.js/Express server with express-stormpath for user authentication, everything runs smoothly without email verification. However, email verification is essential for various reasons; nevertheless, my email-verified users face issues whi ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...