Hello. I’ve created a currency converter app. My app accepts number as input and works well. However, when user types something other than a number or leaves the input field empty, my app does nothing. I want it to return an error notice clarifying that providing a number is required.
This is my current code but it doesn’t work. It even doesn’t throw an error on the console but tries fetching as if number is provided.
input.js:
import React, { useState } from 'react';
const Input = ({ dropdown, onChange, label, symbols }) => {
const arrOfSymbols = Object.keys(symbols);
arrOfSymbols.sort();
const [error, setError] = useState('');
const handleInputChange = (e) => {
const inputValue = e.target.value;
console.log('Input Value:', inputValue);
// Check if the input is empty or not a number
if (inputValue.trim() === '' || isNaN(inputValue)) {
// Set the error state
setError('Please enter a valid number.');
console.log('Error:', 'Please enter a valid number.');
} else {
// If the input is valid, clear the error state
setError('');
// Proceed with the provided onChange callback
onChange(inputValue);
}
};
Input field on input.js:
<input type="number" placeholder="Enter the number you want to convert" className="px-4 py-2 rounded-xl" onChange={handleInputChange} />
Fetching part of index.js:
// FETCH
const convertCurrency = () => {
const options = {
method: "GET",
url: "http://localhost:3000/api/convert",
params: { convertFrom, convertTo, amount },
};
axios.request(options).then(function (response) {
const { data } = response;
setConvertedAmount((data.result));
setError(null); // Clear any previous errors
}).catch(function (error) {
console.error(error);
setError('An error occurred during conversion.'); // Set an error message
});
};
What my console throws when I click on Convert button (triggers convertCurrency function above) while input field is either blank or non-numeric:
GET http://localhost:3000/api/convert?convertFrom=ANG&convertTo=ANG&amount=