Home > database >  react form nor sending data to backend
react form nor sending data to backend

Time:12-08

import React, {useState} from 'react'
import Axios from 'axios'; 

function Review() {
  const url = "/reviews"
  const [data, setData] = useState({
    review: "",
    user_id: "",
    coffee_id: ""
  }) 

function submit(e){
    e.preventDefault();
    Axios.post(url,{
        review: data.review,
        user_id: data.user_id,
        coffee_id: data.coffee_id
    })
    .then(res =>{
        console.log(res.data)
    })
}
  
  function handle(e){
    const newdata={...data}
    newdata[e.target.id] = e.target.value
    setData(newdata)
    console.log(data)
  }
    return(
        <div>
            <form onSubmit={(e) => submit(e)}>
                <input onChange={(e)=>handle(e)} id="review" defaultvalue={data.review} placeholder="review" type="text"></input>
                <input onChange={(e)=>handle(e)} id="userId" defaultvalue={data.user_id} placeholder="userId" type="text"></input>
                <input onChange={(e)=>handle(e)} id="coffeeId" defaultvalue={data.coffee_id} placeholder="coffeeId" type="text"></input>
                <button>submit review</button>
            </form>
        </div>
    )
}

export default Review

I'm trying to write a review and have it added to an endpont, on my console this is the response {id: null, review: 'lets get this party started', user_id: null, coffee_id: null}, it oonly accepts review but not coffee and user id

CodePudding user response:

You are setting the values with the id from your inputs (data.userId) and then trying to access the data with data.user_id.

You need to change one or the other so they match.

  • Related