'Default Values from API in MUI Text field

I have a form that I built using material UI that I would like to have their default values from an API. The main idea is an Edit screen where the user can edit the details and then send them back. However, I cannot seem to get it working at all. First, I get the data using an axios.get request:

      let { id } = useParams();
  const [unit, setUnit] = useState("");
useEffect(() => {
  axios.get(`http://localhost:3001/units/${id}`).then((response) => {
    setUnit(response.data);
  });
}, []);

Then I assign the value I want to a state:

const [name, setName] = useState(unit.name);

Finally, I try to set it as the value (since I read that defaultValue cannot be controlled):

<TextField
            required
            label="Unit Name"
            value={name}
            onChange={(event) => {setName(event.target.value)}}
            fullWidth
            variant="outlined"
          />

However, the field does not contain any value. I tried assigning unit.name to a normal const and assign it to the textfield value and it worked but I could not edit it.



Solution 1:[1]

In your case, you could change the value to the default value and then you could edit it.

<TextField
 required
 label="Unit Name"
 defaultValue={name}
 onChange={(event) => {setName(event.target.value)}}
 fullWidth
 variant="outlined"
 />

Solution 2:[2]

Working solution is setting the name after receiving the Axios request with the data:

setName(response.data.name)

Then set it as the value and using the onChange normally

<TextField
 required
 label="Unit Name"
 value={name}
 onChange={(event) => {setName(event.target.value)}}
 fullWidth
 variant="outlined"
 />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wildgamer
Solution 2 Mohammed Saber