/    Sign up×
Community /Pin to ProfileBookmark

next.js My app doesn’t return an error when input field is invalid

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=

to post a comment
JavaScriptNext.jsReact

0Be the first to comment 😎

×

Success!

Help @rumeysaglg spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...