2

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>
        ))}  
      </>
 );
}
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
  • Change the state to string, add a condition to `handleChange` to allow empty value. – Alexey Lebedev Dec 22 '19 at 16:44
  • What?! The state is of type number, it is auto-generated from open API, I cannot change it, bad besides that, it is totally obvious for me that state type change could solve the problem, this is why I am asking here. – Amir-Mousavi Dec 22 '19 at 16:46
  • The state is defined in your component, it's not clear what you mean by "auto-generated from open API". I suggest updating the question with an explanation why changing the state type wouldn't work for you. – Alexey Lebedev Dec 22 '19 at 16:54
  • @AlexeyLebedev it does not matter where the state is coming from, it is defined as `number` and I am not searching for a change state solution, change to string is such obvious that did not need making a question here – Amir-Mousavi Dec 22 '19 at 16:58
  • 1
    You could also render `NaN` as a an empty string: `value={isNaN(value) ? '' : value}`, but I think changing the state type is cleaner. – Alexey Lebedev Dec 22 '19 at 17:02
  • @AlexeyLebedev Thanks for the answer, the whole time I was thinking for a solution in state level, though it could be handled this easy in input tag itself :) – Amir-Mousavi Dec 27 '19 at 16:52
  • If you like to re-post it as an answer and I accept it – Amir-Mousavi Dec 27 '19 at 16:53

1 Answers1

0

This is really annoying. We hit this ourselves and the only solution I could come up with was to suppress this particular error from being shown to the user.

Scott Schafer
  • 487
  • 3
  • 14