Tainara
Tainara

Reputation: 337

Edit TextField with value already filled doesn't work

I'm beginner with React JS and I'm doing a test project to train my skills.

I have a list of farms being rendered on the screen. The user can click on the button to register a new farm or can click on the property to be able to edit the existing property.

In a single Dialog Modal I do both. The problem is when I try to edit the Input field, it is not working. It doesn't matter what I type and nothing happens.

That's my input field, I'm using TextField from React Material:

<TextField
  id="farmer-name"
  label="Farm Name"
  value={propertyData.farmerName}
  onChange={(event) =>
    changeField("farmerName", propertyData.id, event.target.value)
  }
  className={classes.input}
  InputProps={{
    className: classes.inputContent
  }}
  InputLabelProps={{
    className: classes.inputLabel
  }}
/>

And here's my function that will be able update my data:

const changeField = (field, id, value) => {
  const newPropertyData = { ...propertyData };
  if (newPropertyData.id === id) {
    newPropertyData.field = value;
  }
};

Here's my code, I put in CodeSandBox: https://codesandbox.io/s/spring-breeze-xnv3r?file=/src/index.js

Screen of my application

Can someone help me to edit that´s values? Thanks

Upvotes: 1

Views: 247

Answers (2)

Awais Rafiq Chaudhry
Awais Rafiq Chaudhry

Reputation: 490

You should save state on change in text field

const changeField = (field, id, value) => {
  const newPropertyData = { ...propertyData };
  if (newPropertyData.id === id) {
     // change field value for specific id
     newPropertyData[field] = value;
   }
   // set updated field value into state to show on form
   setPropertyData(newPropertyData);
};

Upvotes: 2

Chris
Chris

Reputation: 6631

You are not actually changing the propertyData stored in the useState hook.

Currently, there will be a new property added called field in the newPropertyData object. However, this variable is never used or stored and you probably don't want the value to be stored in the field property.

The shortest answer is to pass a function to the setPropertyData which will receive the previous value of propertyData.

The previous propertyData can be extended with a dynamic property by using the following syntax: [field]: value.

  const changeField = (field, id, value) => {
    if (propertyData.id === id) {
      setPropertyData(data => ({ ...data, [field]: value }));
    }
  };

Upvotes: 1

Related Questions