From 1fee8984acce51d9022916a63a834988bf28501a Mon Sep 17 00:00:00 2001 From: LongJourney47 Date: Thu, 22 Jun 2023 20:50:10 -0400 Subject: [PATCH] fixed bugs --- components/Calculator.js | 37 ++++++++---------------------- pages/api/calculate/[...params].js | 11 ++++++--- utils/calculate.js | 2 +- 3 files changed, 19 insertions(+), 31 deletions(-) diff --git a/components/Calculator.js b/components/Calculator.js index 9894b49..c34e238 100644 --- a/components/Calculator.js +++ b/components/Calculator.js @@ -23,6 +23,7 @@ const Calculator = () => { const handleChange = (e) => { setOperation(e.target.value); + }; useEffect(() => { @@ -33,14 +34,18 @@ const Calculator = () => { e.preventDefault(); const query = { operation: operation, - first: firstRef.current.value, - second: secondRef.current.value, + first: parseInt(firstRef.current.value), + second: parseInt(secondRef.current.value), }; + + + axios .get(`/api/calculate/${query.operation}/${query.first}/${query.second}`) .then((res) => { setResult(res.data.result); + }) .catch((err) => { console.log(err.response.data.message); @@ -51,8 +56,8 @@ const Calculator = () => { e.preventDefault(); setOperation(""); setResult(welcomeMessage); - firstRef.current.value = null; - secondRef.current.value = null; + firstRef.current.value = ""; + secondRef.current.value = ""; document.activeElement.blur(); }; @@ -107,7 +112,7 @@ const Calculator = () => { - @@ -129,25 +134,3 @@ const Calculator = () => { ); }; export default Calculator; - - - - - - - - - - - - - - - - - - - - - - diff --git a/pages/api/calculate/[...params].js b/pages/api/calculate/[...params].js index b109a39..589e57d 100644 --- a/pages/api/calculate/[...params].js +++ b/pages/api/calculate/[...params].js @@ -1,4 +1,4 @@ -import { add, multiply, divide } from "../../../utils/calculate"; +import { add, subtract, multiply, divide } from "../../../utils/calculate"; export default function handler(req, res) { try { @@ -12,12 +12,17 @@ export default function handler(req, res) { let result; switch (params.operation) { case "add": - result = add(params.first, params.second); + const firstNumber = parseFloat(params.first); + const secondNumber = parseFloat(params.second); + if (isNaN(firstNumber) || isNaN(secondNumber)) { + throw new Error("Invalid numbers provided"); + } + result = add(firstNumber, secondNumber); break; case "subtract": result = subtract(params.first, params.second); break; - case "Multiply": + case "multiply": result = multiply(params.first, params.second); break; case "divide": diff --git a/utils/calculate.js b/utils/calculate.js index 3288ddc..95630d7 100644 --- a/utils/calculate.js +++ b/utils/calculate.js @@ -11,7 +11,7 @@ export const multiply = (first, second) => { }; export const divide = (first, second) => { - return first % second; + return first / second; };