Home > front end >  Sending Form Data From Frontend to Backend Using Axios Using React
Sending Form Data From Frontend to Backend Using Axios Using React

Time:05-24

I am trying to get input from the user in a form field and access the data in my backend server.js . I wanted to use this data in order to pass parameters to the Yelp Fusion API I am using. I know I can use axios for this but am unsure how to accomplish this at this time.

Here is my server.js:

const express = require('express')
const dotenv = require('dotenv').config()
const port = process.env.PORT || 5000
var axios = require('axios');

const app = express()

var cors = require('cors');
app.use(cors());

// app.get('/', (req, res) => {

//     var config = {
//         method: 'get',
//         url: 'https://api.yelp.com/v3/businesses/search?location=Houston',
//         headers: { 
//           'Authorization': 'Bearer <API_KEY>
//         }
//       };
      
//       axios(config)
//       .then(function (response) {
//        //const data = JSON.stringify(response.data);
//        res.json(response.data)
//       })
//       .catch(function (error) {
//         console.log(error);
//       });

// })




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

Here is the App.js in which I need to pass the state from the input field to the backend:

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



function App() {

  const [zip,setZip] = useState("")


  function handleSubmit() {
    useEffect(() => {
      axios.post("http://localhost:8000")
      .then(res => {
        console.log(res)
      })
    })
  }

  // const [results, setResults] = useState({})
  // console.log(results)
  // useEffect(() => {
  //   axios.get('http://localhost:8000').then(res => {
  //     console.log(res)
  //   })
    
  // }, [])
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" name="name" />
        </label>
        <input type="submit" value="Submit" />
    </form>
    </div>
  );
}

export default App;

CodePudding user response:

  1. You use useEffect() function wrongly.

  2. Handle the input element state properly.

  3. To send data to the server you can use axios.post(url,data).then()


import React, { useState } from "react";
import axios from "axios";

function App() {
  const [zip, setZip] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    axios.post("http://localhost:8000", { zip: zip }).then((res) => {
      console.log(res);
    });
  }

  const handleChange = (event) => {
    setZip(event.target.value);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          ZIP:
          <input type="text" value={zip} name="zip" onChange={handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}
export default App;

CodePudding user response:

Ok, here's what's wrong with your code:

  1. hooks can only be placed on the first level of functional component (outside any sub-functions) and must be before any return statements.

  2. Use effect will fire on render, in your code it looks like you wanna trigger it on event click.

I would do it this way if I were you:

function App() {
  const [zip,setZip] = useState("");

  const triggerAPI = useCallback(async () => {
    // Use async await instead of chained promise
    const res = await axios.post("http://localhost:8000", { zip: zip });
    console.log(res)
  }, [zip]);

  const handleSubmit = useCallback((e) => {
    e.preventDefault()
    triggerAPI();
  }, [triggerAPI])

  const handleChange = useCallback((event) => {
    setZip(event.target.value);
  }, []);

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          ZIP:
          <input type="text" value={zip} name="zip" onChange={handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

export default App;

changes:

  1. I used useCallback to memoize the functions
  2. I used async/await instead of chained promise (looks cleaner)
  • Related