Amir-Mousavi
Amir-Mousavi

Reputation: 4593

How to handle NaN in controlled input element with value of type number

In the situation like the code snippet below how should I handle NaN where the state type is number.

The server sends an array of objects:

interface MyInterface {id:number, amount:number, score:number}
// The received data is of type MyInterface[]

So here empty input will result in NaN, Warning: Received NaN for thevalueattribute. If this is expected, cast the value to a string..

In case I check the condition isNaN(parseInt(e.target.value)) what should I update state with? In general in this scenario, how can I have empty input?

const App:React.FC<Props>=(props:Props)=> {
  const [data, setData] = React.useState<MyInterface[]>(props.values);

  const handleChange = (e: ChangeEvent<HTMLInputElement>,id:number) => {
    const amount = parseInt(e.target.value, 10);
    const temp:MyInterface[] = data.map(d => d.id === id? {...d,amount} : d)
    setData(temp);
  };

  const upload = ()=> { /* POST the state array to server */}

  return (
      <>
        {data.map(d=> (
         <div>
           <input value={d.amount} onChange={handleChange} />
           <button onClick={upload}/>
         </div>
        ))}  
      </>
 );
}

Upvotes: 2

Views: 3146

Answers (0)

Related Questions