Fetching method from the backend to use it in the frontend - ReactJS

Viewed 30

I have a problem with fetching my already written method stored in the backend. The method calculates the loan. I need to use it in my frontend in order to display the results of the calculation. Below you can see the code both in the backend file and in the frontend file.

LoanCalculator.js (front-end part)

import React, { useState, useEffect} from 'react';

function LoanCalculator() {
 /*const [data, setData] = useState({
  amount: number,
  numOfMonths: number
});*/

  const [validated, setValidated] = useState(false);
  const [calculateLoadCall, setCalculateLoadCall] = useState({
    state: "inactive",
});

useEffect(() => {

    fetch(`http://localhost:3000/request/calculate`, {
        method: "POST",
        body: {
          amount: "",
          numOfMonths: ""
        },
       
     }).then(async (response) => {
        const responseJson = await response.json();
        if (response.status >= 400) {
          setCalculateLoadCall({ state: "error", error: responseJson });
        } else {
          setCalculateLoadCall({ state: "success", data: responseJson });
        }
    });
}, []);

  // state to storage the values given by the user when filling the input fields
  const [userValues, setUserValues] = useState({
    amount: '',
    numOfMonths: '',
  });

  // state to storage the results of the calculation
  const [results, setResults] = useState({
    monthlyPayment: '',
    yearlyInterest: '',
    RPSN: '',
    overallAmount: '',
    fixedFee: '',
    isResult: false,
  });

  // event handler to update state when the user enters values

  const handleInputChange = (event) =>
    setUserValues({ ...userValues, [event.target.name]: event.target.value });

  

  // Handle the data submited - validate inputs and send it as a parameter to the function that calculates the loan
  const handleSubmitValues = (e) => {
    const form = e.currentTarget;
    e.preventDefault();
    if (!form.checkValidity()) {
      setValidated(true);
      return;
    }
  };

  // Function for calculation

 

  // Method for calculating results calculateResults =

  // Clear input fields
  const clearFields = () => {
    setUserValues({
      amount: '',
      numOfMonths: '',
    });

    setResults({
      monthlyPayment: '',
      yearlyInterest: '',
      RPSN: '',
      overallAmount: '',
      fixedFee: '',
      isResult: false,
    });
  };

  return (
    <div className='calculator'>
      <div className='form'>
        <h1>Online sjednání</h1>
        {/* Display the error when it exists */}
        
        <form onSubmit={handleSubmitValues}>
       {!results.isResult ? (
            //   Form to collect data from the user
            <div className='form-items'>
              <div>
                <label id='label'>Výše úvěru</label>
                <input
                  type='text'
                  name='amount'
                  placeholder='Částka'
                  value={userValues.amount}
                  // onChange method sets the values given by the user as input to the userValues state
                  onChange={handleInputChange}
                  min={5000}
                  max={1200000}
                  required
                />

              </div>

              <div>
                <label id='label'>Doba splacení:</label>
                <input
                  type='text'
                  name='numOfMonths'
                  placeholder='Doba splácení'
                  value={userValues.numOfMonths}
                  onChange={handleInputChange}
                  min={6}
                  max={60}
                  required
                />
              </div>
              <input type='submit' className='button' onChange={setCalculateLoadCall}/>
            </div>
          ) : (
            //   Form to display the results to the user
            <div className='form-items'>
              
              <div>
                <label id='label'>Měsíční splátka:</label>
                <input type='text' value={results.monthlyPayment} disabled />
              </div>
              <div>
                <label id='label'>Roční úrok:</label>
                <input type='text' value={results.yearlyInterest} disabled />
              </div>
              <div>
                <label id='label'>RPSN:</label>
                <input type='text' value={results.RPSN} disabled />
              </div>
              <div>
                <label id='label'>Celková částka ke splacení: </label>
                <input type='text' value={results.overallAmount} disabled />
              </div>
              <div>
                <label id='label'>Poplatek:</label>
                <input type='text' value={results.fixedFee} disabled />
              </div>
              {/* Button to clear fields */}
              <input
                className='button'
                value='Vypočítat znovu'
                type='button'
                onClick={clearFields}
              />
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

export default LoanCalculator;

**And here is the file used for calculation in the backend **

const Ajv = require("ajv").default;

const schema = {
  type: "object",
  properties: {
    amount: {type: "number"},
    numOfMonths: {type: "number"}
  },
  required: ["amount", "numOfMonths"],
};

async function CalculateAbl(req, res) {
  try {
    const ajv = new Ajv({useDefaults: 'empty'});
    const values = req.body;
    const valid = ajv.validate(schema, values);

    const {amount, numOfMonths} = values
    const interest = 9
    const RPSN = 11
    const overall = Math.ceil(amount * 1.11)
    const monthly = Math.ceil(overall / numOfMonths)
    if (valid) {
        const result = {
          monthlyPayment: monthly,
          yearlyInterest: interest,
          RPSN: RPSN,
          overallAmount: overall,
          fixedFee: values.amount > 200000 ? 2000 : 0
        }
      res.status(200).send(result)
    } else {
      res.status(400).send({
        errorMessage: "validation of input failed",
        params: req.body,
      });
    }
  } catch (e) {
    console.log(e);
    res.status(500).send(e.stack);
  }
}

module.exports = CalculateAbl;
0 Answers
Related