Nodejs- How to save my file/ file name to mysql database - mysql

I am trying to save a photo to my database. I have implemented the multer middelware to upload the file to my server. I have a folder called uploads where I am storing my photo. I have successfully renamed the file in my backend with the extension and I am able to get the file in my uploads folder. However, the challenge I am now facing is saving the file name/ file path to mysql database so that I can retrieve it again in my front-end.
editUser.js (front-end form):
import axios from "axios";
import { React, useState, useEffect } from "react";
import { useHistory, withRouter } from "react-router-dom";
function UserMaster_Edit(props) {
const [CmpnyCode, setCmpnyCode] = useState("");
const [UserID, setUserID] = useState("");
const [UserFullName, setUserFullName] = useState("");
const [UserDetail, setUserDetail] = useState("");
const [LoginID, setLoginID] = useState("");
const [Password, setPassword] = useState("");
const [UserPin, setUserPin] = useState("");
const [UserEmailID, setUserEmailID] = useState("");
const [UserFP, setUserFP] = useState({});
const [Photo, setPhoto] = useState({});
const [IsActive, setIsActive] = useState("");
const [LicCount, setLicCount] = useState("");
const [DateCreated, setDateCreated] = useState("");
const [CreatedBy, setCreatedBy] = useState("");
const [RecordChanged, setRecordChanged] = useState("");
const [LocationID, setLocationID] = useState("");
const [isValid, setisValid] = useState("");
const [isDeleted, setisDeleted] = useState("");
const history = useHistory();
const argu = props.match.params.UserID;
useEffect(() => {
axios.get("http://localhost:8000/getuserid/" + argu).then((response) => {
setCmpnyCode(response.data[0].CmpnyCode);
setUserID(response.data[0].UserID);
setUserFullName(response.data[0].UserFullName);
setUserDetail(response.data[0].UserDetail);
setLoginID(response.data[0].LoginID);
setPassword(response.data[0].Password);
setUserPin(response.data[0].UserPin);
setUserEmailID(response.data[0].UserEmailID);
setUserFP(response.data[0].UserFP);
//setPhoto(response.data[0].Photo);
setIsActive(response.data[0].IsActive.data[0]);
setLicCount(response.data[0].LicCount);
setDateCreated(response.data[0].DateCreated);
setCreatedBy(response.data[0].CreatedBy);
setRecordChanged(response.data[0].RecordChanged.data[0]);
setLocationID(response.data[0].LocationID);
setisValid(response.data[0].isValid);
setisDeleted(response.data[0].isDeleted);
});
}, [argu]);
const editData = () => {
axios.put("http://localhost:8000/upusermst/" + argu, {
CmpnyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
// Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
});
history.push("/usermst");
};
const uploadPhoto = (event, argu) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};
return (
<div className="App">
<div className="auth-wrapper">
<div className="auth-inner">
<form enctype="multipart/form-data">
<h3> Edit User Master</h3>
<div>
<div className="form-class8">
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
value={CmpnyCode}
onChange={(e) => {
setCmpnyCode(e.target.value);
}}
name="CmpnyCode"
/>
</div>
<div className="form-group">
<label>UserID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
value={UserID}
onChange={(e) => {
setUserID(e.target.value);
}}
name="UserID"
/>
</div>
<div className="form-group">
<label>UserFullName</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
value={UserFullName}
onChange={(e) => {
setUserFullName(e.target.value);
}}
name="UserFullName"
/>
</div>
<div className="form-group">
<label>UserDetail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetail(e.target.value);
}}
name="UserDetail"
value={UserDetail}
/>
</div>
<div className="form-group">
<label>LoginID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginID(e.target.value);
}}
name="LoginID"
value={LoginID}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="text"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPassword(e.target.value);
}}
name="Password"
value={Password}
/>
</div>
<div className="form-group">
<label>UserPin</label>
<input
type="text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPin(e.target.value);
}}
name="UserPin"
value={UserPin}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailID(e.target.value);
}}
name="UserEmailID"
value={UserEmailID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>UserFP</label>
<input
type="file"
className="form-control"
placeholder="UserFP"
onChange={(e) => {
setUserFP(e.target.value);
}}
name="UserFP"
/>
</div>
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
id="Photo"
name="Photo"
/>
<button onClick={(event) => uploadPhoto(event)}>
Upload
</button>
</div>
<div className="form-group">
<label>IsActive</label>
<input
type="text"
className="form-control"
placeholder="IsActive"
onChange={(e) => {
setIsActive(e.target.value);
}}
name="IsActive"
value={IsActive}
/>
</div>
<div className="form-group">
<label>LicCount</label>
<input
type="text"
className="form-control"
placeholder="LicCount"
onChange={(e) => {
setLicCount(e.target.value);
}}
name="LicCount"
value={LicCount}
/>
</div>
<div className="form-group">
<label>DateCreated</label>
<input
type="text"
className="form-control"
placeholder="DateCreated"
onChange={(e) => {
setDateCreated(e.target.value);
}}
name="DateCreated"
value={DateCreated}
/>
</div>
<div className="form-group">
<label>CreatedBy</label>
<input
type="text"
className="form-control"
placeholder="CreatedBy"
onChange={(e) => {
setCreatedBy(e.target.value);
}}
name="CreatedBy"
value={CreatedBy}
/>
</div>
<div className="form-group">
<label>RecordChanged</label>
<input
type="text"
className="form-control"
placeholder="RecordChanged"
onChange={(e) => {
setRecordChanged(e.target.value);
}}
name="RecordChanged"
value={RecordChanged}
/>
</div>
<div className="form-group">
<label>LocationID</label>
<input
type="text"
className="form-control"
placeholder="LocationID"
onChange={(e) => {
setLocationID(e.target.value);
}}
name="LocationID"
value={LocationID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>isValid</label>
<input
type="date"
className="form-control"
placeholder="isValid"
onChange={(e) => {
setisValid(e.target.value);
}}
name="isValid"
value={isValid}
/>
</div>
<div className="form-group">
<label>isDeleted</label>
<input
type="date"
className="form-control"
placeholder="isDeleted"
onChange={(e) => {
setisDeleted(e.target.value);
}}
name="isDeleted"
value={isDeleted}
/>
</div>
</div>
<button
className="btn btn-primary btn-block"
onClick={() => editData()}
>
Edit
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default withRouter(UserMaster_Edit);
I am trying to work with the "Photo" div here
index.js:
const multer = require("multer");
const fs = require("fs");
const upload = multer({ dest: "uploads/" });
app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) => {
const userid = req.params.userId;
const photo = req.file;
const fileType = photo.mimetype.split("/")[1];
let newFileName = photo.filename + "." + fileType;
fs.rename(
`./uploads/${photo.filename}`,
`./uploads/${newFileName}`,
function () {
console.log("file renamed and uploaded");
}
);
console.log(photo);
console.log("fileName ", newFileName);
db.query(
"UPDATE usermst SET Photo=? WHERE UserID=?",
[newFileName, userid],
(err, result) => {
console.log(err);
res.json({ result });
}
);
});

I just realized what the problem here was. A very minute detail.
In the upload photo function, I am passing two arguments; event and argu.
Argu is undefined hence ther is no userID being passed, it is undefined too.
The function should look like this:
const uploadPhoto = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};```
This should pass the correct userID and update the database as well.

Related

How to Pass JSON data inside HTML attributes

I have created a form using HTML and trying to pass the value of a JSON object in the HTML attribute. I have used fetch to get the data from the api and used it to create options in my page that is made using vueJS. The problem is, the value that gets logged in the database is {{item}} instead of the value in the item.
How to resolve this issue?
AddLog.vue code:
<template>
<h1 style="margin-top: 107px; text-align: center;color: ;">Log the values into the tracker</h1>
<form #submit.prevent="submit" style="margin-right: 522px;margin-top: 29px; margin-left: 519px" method="POST">
<div class="form-group">
<label for="exampleInputEmail1" required style="color: ;">Note</label>
<input type="name" class="form-control" v-model="data.note" id="exampleInputEmail1" aria-describedby="emailHelp" name="Note" placeholder="Note" style="border-radius: 20px;">
</div>
<div class="form-group" v-if="this.trackertype==='Numerical'" >
<label for="exampleInputPassword1" required style="color: ;">Enter the Value</label>
<input type="value" class="form-control" v-model="data.value" id="exampleInputPassword1" name="value" placeholder="Value" style="border-radius: 20px;" required>
</div>
<div class="multiple-choice" v-else>
<label for="value" style="color: ;">Check the value</label>
<div class="form-check">
<div v-for="item,index in this.trackersettings" :key="index">
<input type="radio" name="value" v-model="data.value" value="{{item}}" required>
<label>{{item}}</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline-dark" style="border-radius: 15px;">submit</button>
</form>
</template>
<script>
import { reactive } from 'vue';
import axios from 'axios';
export default {
Name: 'AddLog',
data(){
return{
uid : this.$route.params.uid,
tid : this.$route.params.tid,
items : [],
trackertype: '',
trackersettings: []
}
},
mounted() {
localStorage.setItem('uid',this.uid)
localStorage.setItem('tid',this.tid)
axios.get('http://localhost:5000/addLog/'+this.uid+'/'+this.tid)
.then((resp ) => {
this.items = resp.data
this.trackertype = this.items[0]['data']['trackertype']
this.trackersettings =this.items[1]['tracker_settings']
console.log(this.trackertype,this.trackersettings)
})
.catch((err) => {
console.log(err.resp)
})
},
setup() {
const data = reactive({
note: '',
value: ''
})
const submit = async () => {
await fetch("http://localhost:5000/addLog/"+localStorage['uid']+'/'+localStorage['tid'],{
method: 'POST',
headers: {'Content-Type' : 'application/json','Access-Control-Allow-Origin': '*'},
body: JSON.stringify(data)
}).then(resp => resp.json())
.then(data => {console.log(data);})
.catch(error => { console.log(error)
})
}
return {
data,
submit,
}
}
}
</script>
<style>
</style>
API code:
#app.route('/addLog/<int:uid>/<int:tid>', methods=['GET', 'POST'])
def log(uid,tid):
cell = tracker.query.filter_by(u_id=uid,tracker_id=tid).first()
l = cell.tracker_settings.split(',')
d = {
'userid' : cell.u_id,
'trackerid' : cell.tracker_id,
'trackername' : cell.tracker_name,
'trackerdesc' : cell.tracker_description,
'trackertype' : cell.tracker_type,
'tracker_settings' : cell.tracker_settings,
'datecreated' : cell.date_created
}
if request.method=='POST':
data = request.json
val = data['value']
note = data['note']
cell = logtable(user_id=uid,t_id=tid,Note=note,value=val)
db.session.add(cell)
db.session.commit()
return jsonify({'message':'success'})
else:
return jsonify({'data':d},{'tracker_settings' : l })
I want the values in the options to be logged in the db.
Instead of the "{{item}}" in the value , I need the string "Gloomy". Can Anybody help me on doing this?
Here is the correct way to assign the value :
Try :value="item" instead of value="{{item}}"
Demo :
var app = new Vue({
el: '#app',
data: {
selected: '',
item1: 'Male',
item2: 'Female'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Binding Radio</h2>
<input type="radio" id="one" :value="item1" v-model="selected">
<label for="one">Male</label>
<br>
<input type="radio" id="two" :value="item2" v-model="selected">
<label for="two">Female</label>
<br>
<span>Picked: {{ selected }}</span>
</div>

reactjs how to get previous user detail with html select?

I'm new to react, and looks like I'm following the tutorial with an old version of react. So, I have some users with their role, and the problem is when I want to make changes to the user role I want it to select the previous user role for preview (not the default value, in this case "admin").
userEdit.tsx
import axios from "axios";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { Navigate, useParams } from "react-router-dom";
import Wrapper from "../../components/Wrapper";
import { Role } from "../../models/role";
const UserEdit = (props: any) => {
const [first_name, setFirstName] = useState('');
const [last_name, setLastName] = useState('');
const [email, setEmail] = useState('');
const [role_id, setRoleId] = useState('');
const [roles, setRoles] = useState([]);
const [redirect, setRedirect] = useState(false);
const {id} = useParams();
useEffect(() => {
(
async () => {
const response = await axios.get('roles');
setRoles(response.data);
const {data} = await axios.get(`users/${id}`);
setFirstName(data.first_name);
setLastName(data.last_name);
setEmail(data.email);
setRoleId(data.role_id);
}
)()
}, [id]);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await axios.put(`users/${id}`, {
first_name,
last_name,
email,
role_id
});
setRedirect(true)
}
if(redirect) {
return <Navigate to="/users"/>
}
return (
<Wrapper>
<form onSubmit={submit}>
<h1 className="h3 mb-3 fw-normal">Edit user</h1>
<div className="form-floating">
<input className="form-control" placeholder="First Name" defaultValue={first_name} onChange={e => setFirstName(e.target.value)} required/>
<label htmlFor="floatingInput">First Name</label>
</div>
<div className="form-floating">
<input className="form-control" placeholder="Last Name" defaultValue={last_name} onChange={e => setLastName(e.target.value)} required/>
<label htmlFor="floatingInput">Last Name</label>
</div>
<div className="form-floating">
<input type="email" className="form-control" placeholder="Email Address" defaultValue={email} onChange={e => setEmail(e.target.value)} required/>
<label htmlFor="floatingInput">Email Address</label>
</div>
<div className="form-floating">
<select className="form-control" value={role_id} onChange={e => setRoleId(e.target.value)}>
{roles.map((r: Role) => {
return (
<option key={r.id} value={r.id}>{r.name}</option>
)
})}
</select>
<label>Role</label>
</div>
<button className="w-100 btn btn-lg btn-primary" type="submit">Save</button>
</form>
</Wrapper>
);
};
export default UserEdit;
As you can see I'm using "value={role_id}" to get the previous user role, but it seems to not be working. Please help me so I can continue the tutorial.
try setting defaultValue = {role_id} instead of value

Trying to add scroll event listener on window, but getting Uncaught TypeError: Cannot read property 'classList' of null

I am trying to add the bottom shadow to the search bar on scroll in react js. it is working well until I go on the second page of my app.
When I am trying to go on the second page, it showing
Uncaught TypeError: Cannot read property 'classList' of null
Not working code :
import React, { useEffect } from 'react';
import { AiOutlineSearch } from "react-icons/ai";
const SearchBar = ({ totalPrograms, programs, setPrograms }) => {
const handleScroll = () => {
if(window.scrollY) {
document.getElementById('sb-header').classList.add('h-shadow');
}
else {
document.getElementById('sb-header').classList.remove('h-shadow');
}
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {window.removeEventListener('scroll', handleScroll)};
},[]);
const handleSubmit = (event) => {
event.preventDefault();
const searchProgramName = document.getElementById('search').value;
if(searchProgramName) {
setPrograms(
programs.filter(program =>
program.name.toLowerCase().includes(searchProgramName)
)
);
}
else {
handleClick();
}
}
const handleClick = () => {
const allPhase = document.getElementsByName('phase');
const checkedPhaseValue = [];
allPhase.forEach(phase => {
if(phase.checked) {
checkedPhaseValue.push(phase.value);
}
});
setPrograms(checkedPhaseValue.length ?
totalPrograms.filter(
program => checkedPhaseValue.includes(program.phase.toLowerCase())
)
: totalPrograms
);
}
return (
<header id='sb-header' className="container header-sb">
<form className="container container-center" onSubmit={handleSubmit}>
<div className="type-search">
<AiOutlineSearch className="icon"/>
<input id="search" type="search" placeholder="search by program name"/>
</div>
<div className="checkbox-container">
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="open_application" value="application_open"/>
<label htmlFor="open_application">Open Application</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="application_in_review" value="application_review"/>
<label htmlFor="application_in_review">Application in Review</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="in_progress" value="in_progress"/>
<label htmlFor="in_progress">in Progress</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="completed" value="completed"/>
<label htmlFor="completed">Completed</label>
</div>
</div>
</form>
</header>
)
}
export default SearchBar;
On the second page, I am going by clicking on the Details button. Code for that :
import React from 'react';
import { Link } from 'react-router-dom';
import { FaAngleDoubleRight } from 'react-icons/fa';
import * as ROUTES from '../Constants/routes';
const ProgramCards = ({ program }) => {
return (
<div className="card">
<div className="card-header">
<h1 className="p-name">{program.name}</h1>
</div>
<div className="card-body">
<h3 className="p-category">{program.category}</h3>
<small className="p-phase">{(program.phase).replace('_', ' ')}</small>
<p className="p-description">{program.shortDescription}</p>
</div>
<div>
<div className="date-duration">
<small className="p-date">Start Date: {program.startDate}</small>
<small className="p-duration">Duration: {program.duration}</small>
</div>
<Link to={ROUTES.PROGRAM_DETAILS}>
<button className="card-button">
Details <FaAngleDoubleRight className="icon angled-icon" />
</button>
</Link>
</div>
</div>
)
}
export default ProgramCards;
My question is, why it is not working?
After this, I tried a different approach. And it is working well.
Working code :
import React, { useEffect, useState } from 'react';
import { AiOutlineSearch } from "react-icons/ai";
const SearchBar = ({ totalPrograms, programs, setPrograms }) => {
const [ scrolled, setScrolled ] = useState(false);
const handleScroll = () => {
if(window.scrollY > 10) {
setScrolled(true);
}
else {
setScrolled(false);
}
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {window.removeEventListener('scroll', handleScroll)};
},[]);
const handleSubmit = (event) => {
event.preventDefault();
const searchProgramName = document.getElementById('search').value;
if(searchProgramName) {
setPrograms(
programs.filter(program =>
program.name.toLowerCase().includes(searchProgramName)
)
);
}
else {
handleClick();
}
}
const handleClick = () => {
const allPhase = document.getElementsByName('phase');
const checkedPhaseValue = [];
allPhase.forEach(phase => {
if(phase.checked) {
checkedPhaseValue.push(phase.value);
}
});
setPrograms(checkedPhaseValue.length ?
totalPrograms.filter(
program => checkedPhaseValue.includes(program.phase.toLowerCase())
)
: totalPrograms
);
}
return (
<header className={`container header-sb ${scrolled && 'h-shadow'}`}>
<form className="container container-center" onSubmit={handleSubmit}>
<div className="type-search">
<AiOutlineSearch className="icon"/>
<input id="search" type="search" placeholder="search by program name"/>
</div>
<div className="checkbox-container">
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="open_application" value="application_open"/>
<label htmlFor="open_application">Open Application</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="application_in_review" value="application_review"/>
<label htmlFor="application_in_review">Application in Review</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="in_progress" value="in_progress"/>
<label htmlFor="in_progress">in Progress</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="completed" value="completed"/>
<label htmlFor="completed">Completed</label>
</div>
</div>
</form>
</header>
)
}
export default SearchBar;
Your second approach is the better and the react way to do it. It is generally discouraged to query the DOM managed by react yourself. Use ref's if you need the DOM node.
The first example is not working because handleScroll will be recreated every time the component re-renders. Therefore removing the listener will not remove the original listener as the function referenced by handleScroll has changed.
Therefore when your component unmounts the listener will not be removed correctly but react will remove the DOM node. Next time you scroll the handler will still be called but the node you are trying to query isn't there anymore.
You have to create the listener inside of useEffect so that your removeEventListener references the correct function:
useEffect(() => {
const handleScroll = () => setScrolled(window.scrollY > 10);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
},[]);
Alternatively you could use useRef to create a stable reference to you listener function.

How to correctly update form, react state with axios post request?

I'm currently making a post request using axis but the data I pass into my form isn't being updated.
I keep receiving a 404 error.I think it might be the form info isn't being passed to the post request.
I do think my logic is correct, the only issue I can think go is how I'm accessing the address object in my state maybe or how the keys in address is accessed in the input tags.
This is how the JSON POST body should be:
{
"first_name": "Craig",
"last_name": "Williams",
"address": {
"line_1": "123 Mark Lane",
"line_2": "3B",
"city": "Brooklyn",
"region": "NY",
"postal": "41211"
}
}
Current after the form is filled out I console log the state in onSubmit nd this is what is logged. It's incorrect, it should be more like the JSON body.
{first_name: "Craig",
last_name: "Williams",
address: "123 Mark Lane",
line_2: "41211"}
Currently my code looks like this:
import React from 'react';
import axios from 'axios';
class App extends React.Component{
state = {
first_name : '',
last_name : '',
address : {
line_1: '',
line_2: '',
city: '',
state: '',
zipcode: ''
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit = (e) => {
e.preventDefault();
const {first_name,last_name,address} = this.state;
console.log(address)
axios.post(`website to hit`,{first_name,last_name,address})
.then((result) => {
this.setState({ result.data });
}) .catch((error)=> {
console.log(error);
});
}
render() {
const { first_name, last_name, address } = this.state;
return (
<div className="App">
<div className="left">
<h1>Rocket Insurance</h1>
<h1 className='p-left'>As interplanetary travel becomes mainstream </h1>
</div>
<div className="right">
<h2>Recieve a free qoute today</h2>
<div className="form">
<form onSubmit={this.onSubmit}>
<input
type="text"
name="first_name"
placeholder='First Name'
value={first_name}
onChange={this.onChange}
/>
<input
type="text"
name="last_name"
placeholder='Last Name'
value={last_name}
onChange={this.onChange}
/>
<input
type="text"
name="address"
placeholder='Street'
value={address['line_1']}
onChange={this.onChange}
/>
<input
type="text"
name="line_2"
placeholder='Apt number'
value={address['line_2']}
onChange={this.onChange}
/>
<input
type="text"
name="line_2"
placeholder='City'
value={address['city']}
onChange={this.onChange}
/>
<input
type="text"
name="line_2"
placeholder='State'
value={address['region']}
onChange={this.onChange}
/>
<input
type="text"
name="line_2"
placeholder='zipcode'
value={address['region']}
onChange={this.onChange}
/>
<button className='button-sign-in'>Log in</button>
</form>
</div>
</div>
</div>
);
}
}
export default App;
In should resolve your issue. Your input names were not matching the state values you were trying to change. Your handleChange handler was not designed to handle nested objects however, so i rather flattened your state and on submit, i structure the state to resemble the required object shape for post
class Form extends React.Component {
state = {
first_name: "",
last_name: "",
line_1: "",
line_2: "",
city: "",
state: "",
zipcode: ""
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
onSubmit = e => {
e.preventDefault();
const { first_name, last_name, ...address } = this.state;
console.log({ first_name, last_name, address: { ...address } });
// axios.post(`https://fed-challenge-api.sure.now.sh/api/v1/quotes`,{ first_name, last_name, address: { ...address } })
// .then((result) => {
// console.log("QUOTE:",result)
// this.setState({ result.data });
// }) .catch((error)=> {
// console.log(error);
// });
};
render() {
const {
first_name,
last_name,
zipcode,
line_1,
line_2,
city,
state
} = this.state;
return (
<div className="App">
<div className="left">
<h1>Rocket Insurance</h1>
<h1 className="p-left">
As interplanetary travel becomes mainstream, we're excited to offer
rocket owners comprehensive coverage options to let them fly through
space worry-free{" "}
</h1>
</div>
<div className="right">
<h2>Recieve a free qoute today</h2>
<div className="form">
<form onSubmit={this.onSubmit}>
<input
type="text"
name="first_name"
placeholder="First Name"
value={first_name}
onChange={this.onChange}
/>
<input
type="text"
name="last_name"
placeholder="Last Name"
value={last_name}
onChange={this.onChange}
/>
<input
type="text"
name="line_1"
placeholder="Street"
value={line_1}
onChange={this.onChange}
/>
<input
type="text"
name="line_2"
placeholder="Apt number"
value={line_2}
onChange={this.onChange}
/>
<input
type="text"
name="city"
placeholder="City"
value={city}
onChange={this.onChange}
/>
<input
type="text"
name="state"
placeholder="State"
value={state}
onChange={this.onChange}
/>
<input
type="text"
name="zipcode"
placeholder="zipcode"
value={zipcode}
onChange={this.onChange}
/>
<button className="button-sign-in">Log in</button>
</form>
</div>
</div>
</div>
);
}
}
export default Form;

I am unable to render the JSON object that is being displayed as the response

The Previous issue of getting status 400 error has been resolved , I am able to retrieve the response as a JSON Object , I am here with attaching the modified code , The received JSON response is being stored in the JSON Object :
response_jsonObj , The output is in this format
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...}
0: { id: "value od id", name: "value of name" , field1: "value of field1" , field2: "value of field2" , ...} and so forth, I need to display this in the tabular format , I have followed the examples on stack overflow and am unable to replicate it , Any inputs are welcome .
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { responsedata:[{"id":"","name":"","field1":"","field2":""}] }
}
handleSubmit(event) {
event.preventDefault();
const form = event.target;
const data = new FormData(form);
const arrayValue = [];
var i = 0;
console.log('Data from Form:',data);
for (let name of data.keys()) {
const input = form.elements[name];
const parserName = input.dataset.parse;
const parsedValue = data.get(name);
console.log('name',name);
console.log('parsedValue',parsedValue);
data.set(name, parsedValue);
arrayValue[i] = parsedValue;
i=i+1;
}
console.log('id:after get',arrayValue[0]);
console.log('field1:after get',arrayValue[2]);
console.log('field7:after get',arrayValue[8]);
var response_data = "";
var response_jsonObj ;
var txt = "";
var req = {"CustomerLookupRequest" : [{
"id":arrayValue[0],
"name": "",
"field1":arrayValue[2],
"field2":"",
"field3":"",
"field4":"",
"field5":"",
"field6":"",
"field7":arrayValue[8],
"field8":"",
"field9":"",
"fied10":"",
"field11":""
}]
};
console.log('req string :' + req);
fetch('API_URL', {
headers: {
'Accept': 'application/json, text/plain, application/xml, */*',
'Content-Type': 'application/json' ,
'Access-Control-Allow-Headers': 'Content-Type',
},
method: 'POST',
body: JSON.stringify(req)}
).then(function(response) {
if (response.status !== 200) {
console.log('Problem in fetching');
return;
}
response.text().then(function(data) {
console.log('Data in Console',data);
response_data = data;
console.log('Response Data',response_data);
response_jsonObj = JSON.parse(response_data);
console.log('Response JSON Object',response_jsonObj);
});
}).catch(error => this.setState({ error }));
}
render() {
return (
<div id = "id1">
<form onSubmit={this.handleSubmit}>
<label htmlFor="id">Enter id</label>
<input id="id" name="id" type="text" />
<label htmlFor="name">Enter Name</label>
<input id="name" name="name" type="text" />
<label htmlFor="Field1">Enter your Field1</label>
<input id="Field1" name="Field1" type="text" />
<label htmlFor="Field2">Enter your Field2</label>
<input id="Field2" name="Field2" type="text" />
<label htmlFor="Field3">Enter your Field3</label>
<input id="Field3" name="Field3" type="text" />
<label htmlFor="Field4">Enter your Field4</label>
<input id="Field4" name="Field4" type="text" />
<label htmlFor="Field5">Enter your Field5</label>
<input id="Field5" name="Field5" type="text" />
<label htmlFor="Field6">Enter your Field6</label>
<input id="Field6" name="Field6" type="text" />
<label htmlFor="Field7">Enter your Field7</label>
<input id="Field7" name="Field7" type="text" />
<label htmlFor="Field8">Enter your Field8</label>
<input id="Field8" name="Field8" type="text" />
<label htmlFor="Field9">Enter your Field9</label>
<input id="Field9" name="Field9" type="text" />
<label htmlFor="Field10">Enter your Field10</label>
<input id="Field10" name="Field10" type="text" />
<label htmlFor="Field11">Enter your Field11</label>
<input id="Field11" name="Field11" type="text" />
<button>Send data!</button>
</form>
</div>
);
}
}
export default App;
I'm not sure your fetch format is correct. Do this way.
fetch(POSTAPIURL, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
String1:"xyzabc",
String2:"ABCD"
})
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch( err => {
console.log(err);
});