Kestal
Kestal

Reputation: 223

Input field not binding with the state

I'm trying to bind the input to the state. When doing so I'm stuck where the input value is being captured in onChange function and updated to the state however the JSON object ({JSON.stringify(data.MetricsData)}) that's on the UI doesn't update.

The output result should JSON.stringify(data.MetricsData) to be updated with the latest value that's on the input.

The following is the simplified code:

let obj = [];

function Metrics() {
  obj["MetricsData"] = MetricsDataObj()
  const [data, setData] = useState(obj);

  function onChange(event){
    let value = event.target.value;
    data.MetricsData[0].year1 = value;
    setData(() => {
      console.log(data)
      return data;
    });
  }

  return (
    <div>
      <input type="number" placeholder="0.00" min="0.00" step="0.01" onChange={(e) => onChange(e)} />
      <br/><br/>
      {JSON.stringify(data.MetricsData)}
    </div>
  );
}

function MetricsDataObj(){
  return [
    { id: 1, name: 'Month 1', year1: '' }
  ];
}

export default Metrics;

Upvotes: 0

Views: 39

Answers (1)

Majid M.
Majid M.

Reputation: 4954

You need to make a copy from the state before update its value. In addition the way which you have selected for updating the state is not correct. Try this:

import { useState } from "react";

let obj = [];
function Metrics() {
  obj["MetricsData"] = MetricsDataObj()
  const [data, setData] = useState(obj);

  function onChange(event){
    let value = event.target.value;
    const copy = {...data};
    copy.MetricsData[0].year1 = value;
    setData(copy);
  }

  return (
    <div>
      <input type="number" placeholder="0.00" min="0.00" step="0.01" onChange={(e) => onChange(e)} />
      <br/><br/>
      {JSON.stringify(data.MetricsData)}
    </div>
  );
}

function MetricsDataObj(){
  return [
    { id: 1, name: 'Month 1', year1: '' }
  ];
}

export default function App() {
  return (
    <Metrics/>
  );
}

Edit smoosh-grass-v8qyhb

Upvotes: 1

Related Questions