0

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;
1
  • 1
    Try passing value to <input /> to make it controlled, <input value={data.MetricsData[0]} /> something like so Commented Mar 16, 2022 at 22:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.