Home > Software design >  The specified value "[object Object]" cannot be parsed, or is out of range
The specified value "[object Object]" cannot be parsed, or is out of range

Time:12-19

I am trying to make a currency converter application with React but on my console, after typing in a number in my input, I get a warning saying "The specified value "[object Object]" cannot be parsed, or is out of range."

Here is the relevant code:

const App = () => {
  const [value, setValue] = useState(0);
  const [currencyState, setCurrencyState] = useState('');

  const dollar = 'Dollar';
  const shekel = 'Shekel';

  const handleDollarChange = (value) => {
    setValue({ value });
    setCurrencyState('Dollar');
  };

  const handleShekelChange = (value) => {
    setValue({ value });
    setCurrencyState('Shekel');
  };

  const val = value;
  const currency = currencyState;
  const dollars = currency === 'Dollar' ? tryConvert(val, toShekels) : val;
  const shekels = currency === 'Shekel' ? tryConvert(val, toDollars) : val;

  return (
    <div className="App">
      <CurrencyInput
        value={dollars}
        currency={dollar}
        onChange={handleDollarChange}
      />
      <CurrencyInput
        value={shekels}
        currency={shekel}
        onChange={handleShekelChange}
      />
    </div>
  );
};

And here is the original CurrencyInput code:

const CurrencyInput = (props) => {
  const handleSubmit = (e) => {
    e.preventDefault();
    alert('Your currency has been converted');
  };

  const handleChange = (e) => {
    props.onChange(e.target.value);
  };

  const value = props.value;
  const currency = props.currency;

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Enter {currency}s: &nbsp;
          <input type="number" value={value} onChange={handleChange} />
        </label>
      </form>
    </div>
  );
};

CodePudding user response:

You’re calling setValue({ value }), which passes an object containing a single key value. You probably meant to write setValue(value) instead.

CodePudding user response:

const App = () => {
  const [value, setValue] = useState(0);
  const [currencyState, setCurrencyState] = useState('');

  const dollar = 'Dollar';
  const shekel = 'Shekel';

  const handleDollarChange = (value) => {
    setValue(value);
    setCurrencyState('Dollar');
  };

  const handleShekelChange = (value) => {
    setValue(value);
    setCurrencyState('Shekel');
  };

  const val = value;
  const currency = currencyState;
  const dollars = currency === 'Dollar' ? tryConvert(val, toShekels) : val;
  const shekels = currency === 'Shekel' ? tryConvert(val, toDollars) : val;

  return (
    <div className="App">
      <CurrencyInput
        value={dollars}
        currency={dollar}
        onChange={handleDollarChange}
      />
      <CurrencyInput
        value={shekels}
        currency={shekel}
        onChange={handleShekelChange}
      />
    </div>
  );
};
  • Related