Axios React POST and GET data concurrently when button is clicked

Viewed 19

I've created an app and I'm trying to create and post data into a server and get the data that was just posted at the same time. I want to do this either concurrently or subsequently. In the app I have a form that takes in the input and sends it to the server when a button is clicked,I also want that data to be displayed from the server onto the frontend; theres one function to post the data and another to get the data but what I'm trying to do is both post and get data all using one function and its not working.
Client code

import React, { useState, useRef } from 'react';
import axios from 'axios'
import './App.css';

function App() {
  const [cardHolder, setCardHolder] = useState("");
  const [cardNumber, setCardNumber] = useState("");
  const cardHolderRef = useRef("");
  const balanceRef = useRef("");
  const [balance, setBalance] = useState("");
  const [expDate, setExpDate] = useState("");
  const [cvc, setCvc] = useState("");


  // This is the code for getting data
  async function getCardData() {
    await axios.get("http://localhost:5000/", { crossdomain: true })
      .then(response => {
        setCardHolder(response.data.data.name_on_card);
        setCardNumber(response.data.data.card_pan);
        setBalance(response.data.data.amount + "  " + response.data.data.currency);
        setExpDate(response.data.data.expiration);
        setCvc(response.data.data.cvv);
      })
  };

  // This is the code for creating/posting data
  async function createCardData(e) {
    e.preventDefault();

    await axios.post("http://localhost:5000/", {
      cardHolder: cardHolderRef.current.value,
      balance: balanceRef.current.value
    });

    getCardData();// I tried adding the get data function to this but nothing happened
  };

  return (
    <div>
      <div className='vcard'>
        <div className='theBalance'>
          <h2>{balance}</h2>
        </div>
        <div className='numNcvc'>
          <h2 className='theNum'>{cardNumber}</h2>
          <h2 className='theCvc'>{cvc}</h2>
        </div>
        <div className='expNholder'>
          <h2>Expiry Date<br/> {expDate}</h2>
          <h2>Card Holder<br/> {cardHolder}</h2>
        </div>
      </div>

      <div className='details-div'>
        <form className='details'>
          <input 
            placeholder='Name on Card' 
            type="text" 
            id='cardholder'
            name='cardholder'
            ref={cardHolderRef}></input>
          <input 
            placeholder='Amount (in USD)' 
            type="text"
            id="cardbalance"
            name="cardbalance"
            ref={balanceRef}></input>
          <input placeholder='MTN MoMo Number' type="text"></input>
        </form>
        <button className='createCardBtn' onClick={createCardData}>
          Create Card
        </button>
      </div>
    </div>
  );
}

export default App;

Server/Node code

const { response } = require('express');
const express = require('express');
const cors = require('cors');
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const jsonParser = bodyParser.json();

const Flutterwave = require('flutterwave-node-v3');
const flw = new Flutterwave("FLWPUBK_TEST-63a79c5a6fe457d75a611b0f376e3e53-X", "FLWSECK_TEST-a6281194ef4ca095e794a1681fe32d69-X");

app.use(bodyParser.json());

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

app.post("/", jsonParser, async (req, res) => {
    const cardHolder = req.body.cardHolder;
    const balance = req.body.balance;
    console.log(cardHolder);
    console.log(balance);

    // Payload: Flutterwave Card Details
    const payload = {
        "currency": "USD",
        "amount": balance,
        "billing_name": cardHolder,
        "billing_address": "2014 Forest Hills Drive",
        "billing_city": "React",
        "billing_state": "NY",
        "billing_postal_code": "000009",
        "billing_country": "US",
    }

    flw.VirtualCard.create(payload)
    .then(response => {
        console.log(response);

        app.use(function(req, res, next) {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
            next();
          });

        app.get("/", cors(), async (req, res) => {
            res.send(response)
        });
    });
});

app.listen(5000, () => {console.log("Server started on port 5000")})

//createVcard();

One thing I tried is making two separate buttons; one for each function and it ended up working like how I needed it to but I want it all to work concurrently as soon as I click the button so that the data is sent to the server and displayed to the client at the same time.

0 Answers
Related