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

The Checkboxlist generated by jQuery-Ajax does not function when clicked on

I have a dynamic radio button list (rblCategories) that, when the selected value changes, triggers the creation of a checkbox list using ajax and populates it. However, I am facing an issue with updating my datatable when any checkbox is checked/unchecked ...

Updating a Mongo Record using the ID obtained from another Record's retrievalI hope this meets your needs

One of my current tasks involves creating an API endpoint with specific functionality. The goal is to input an Object ID into the path, locate the record associated with that ID, access a particular field within this object which contains another ObjectID ...

Leveraging the power of Material-UI and React, modify the appearance of the "carrot" icon within the

Currently implementing MUI's textfield based on the information found at this link: https://mui.com/components/text-fields/. While there are numerous resources available for changing the font of the input text, I have not come across any documentation ...

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

The default skin of video.js is disrupted by a 16:8 ratio

Incorporating videojs into my react application has presented a challenge. I have enclosed the video player in a div set to a 16:8 ratio, but unfortunately the default skin does not display properly. On the other hand, when I implement code that includes t ...

Implement the export of components by utilizing the withStyles() and compose() functions in conjunction with Redux, Firebase, and

Currently, I'm in the process of creating an app using firebase and redux for storage, as well as Material UI for design. Everything is functioning smoothly with the firebase and firestore reducers, but I encounter a problem when attempting to export ...

Using Selenium in conjunction with browsermob-proxy to generate new HAR files for redirected web pages

Another interesting scenario I have encountered involves combining Selenium with browsermob-proxy: A new Har is created for the initial page access The initial request can be redirected multiple times And then further redirected by JavaScript For exampl ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

Buttons to maximize, minimize, and close individual sections on a webpage

I am fairly new to front end development and I must say, I am absolutely enjoying every bit of it. Here is a little challenge that came my way. It may seem simple to some but it got me thinking. I have three sections on the right side of my website. I wa ...

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

Trigger a function on q-select change using onChange event (Quasar Framework)

I'm trying to get the function to run when I change the selected value, but it's not working. How can I solve this issue? Below is the code I am using: <q-select v-model="single" :options="['def', 'abc', ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

HTML text not lining up with SVG text

Why is the positioning of SVG Text slightly off when compared to CSS text with the same settings? The alignment seems awkwardly offset. Any help in understanding this would be much appreciated! Even with x: 50% and the relevant text-anchor property set to ...

Upon inserting Node 5, an error with the code EINVALIDTYPE occurred in npm

Recently, after I upgraded to Node 5, I've been encountering an error in the terminal every time I try running anything with npm. npm -v: 2.14.12 Desperately attempting to update npm to the latest version: MacBook-Pro-de-MarceloRS:promo-auto-loan ...

What is the best way to convert the information from a <SelectInput /> component or similar components into another language?

Within my React admin v3 application, When retrieving data from the servers for my entity, I receive a unique identifier called a slug. This slug is a special key that needs to be translated on the client side. Here is an example of my <CallMeBackCre ...

Click on the button to add a new question and watch as another row magically appears

Working with ReactJS My goal is to display 10 rows by default, followed by a button labeled "Add a new question" which would create the 11th row. View current row image here Currently, only one row is being shown [referencing the image below]. I aim to ...