How do I make a POST request using axios in react? - javascript

I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated!
Full Code:
import axios from 'axios';
import React, { useState } from 'react';
import { Container, Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
const AddContact = () => {
const [first_name, setFirstName] = useState("")
const [last_name, setLastName] = useState("")
const [mobile_number, setMobileNumber] = useState("")
const [home_number, setHomeNumber] = useState("")
const [work_number, setWorkNumber] = useState("")
const [email_address, setEmailAddress] = useState("")
const history = useNavigate();
const AddContactInfo = async () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
await axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
return (
<div>
<h1>Add contact</h1>
<Container>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your First Name"
first_name="first_name"
value={first_name}
onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
last_name="last_name"
value={last_name}
onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Mobile Number"
mobile_number="mobile_number"
value={mobile_number}
onChange={(e) => setMobileNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Home Number"
home_number="home_number"
value={home_number}
onChange={(e) => setHomeNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Work Number"
work_number="work_number"
value={work_number}
onChange={(e) => setWorkNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Email Address"
email_address="email_address"
value={email_address}
onChange={(e) => setEmailAddress(e.target.value)} /></div>
<Button onClick={() => { AddContactInfo(); }}>
Add Contact
</Button>
</Container>
</div >
);
};
export default AddContact;

First rename AddContactInfo to addContactInfo and then:
<Button onClick={addContactInfo}>
Add Contact
</Button>
You should correct the method addContactInfo as below:
const AddContactInfo = () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}

Try This:
<Button onClick={AddContactInfo}>
Add Contact
</Button>
import axios from 'axios';
const url = 'http://localhost:8000/api/';
axios.post(url , formField)
.then(response => {
console.log(response.data);
history('/', { replace: true });
})
.catch(({response}) => {
console.log(response);
});

Try calling the function this way :)
<Button onClick={AddContactInfo}>
Add Contact
</Button>

Related

Error message, Warning Cannot update a component (`BrowserRouter`) while rendering a different component

So ive got this error, im guessing its something with my use navigate, but im not shure.
Ive have read alot and searched for the solution but i cant find any way to solve the issue.
The issue only comes after ive have logged in. At the moment i dont have any access token on the backend.
react_devtools_backend.js:4026 Warning: Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Login (http://localhost:3000/static/js/bundle.js:3571:82)
at div
at LoginPage
at Routes (http://localhost:3000/static/js/bundle.js:129199:5)
at Router (http://localhost:3000/static/js/bundle.js:129132:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:127941:5)
import React from 'react';
import { useRef, useState, useEffect } from 'react'
// import { useContext } from 'react'
//import AuthContext from './context/AuthProvider';
import axios from './api/axios';
const LOGIN_URL = '/login';
const REG_URL = '/newUser'
export default function Login() {
const [authMode, setAuthMode] = useState("signin");
const changeAuthMode = () => {
setAuthMode(authMode === "signin" ? "signup" : "signin");
}
//const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
const [register, setRegister] = useState(false);
useEffect(() => {
userRef.current.focus();
}, [])
useEffect(() => {
setErrMsg('');
}, [userName, password])
const handleRegister = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const RegConfiguration = {
method: "post",
url: REG_URL,
data: {
userName,
password,
},
};
// make the API call
axios(RegConfiguration)
.then((result) => {
setRegister(true);
})
.catch((error) => {
error = new Error();
});
};
///HANDLE Login part.
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post(LOGIN_URL,
JSON.stringify({ userName, password }),
{
headers: { 'Content-type': 'application/json' },
withCredentials: false,
}
);
//const token = response?.data?.token;
//setAuth({ userName, password, token })
//console.log(JSON.stringify(respone));
setUserName('');
setPassword('');
setSuccess(true);
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else if (err.response?.status === 400) {
setErrMsg('Missing Username or Password');
} else if (err.response?.status === 401) {
setErrMsg('Unauthorized');
}
else {
setErrMsg('Login Failed');
}
errRef.current.focus();
}
}
const Navigate = useNavigate();
if (authMode === "signin") {
return (
<> {success ? (
Navigate('/authlog')
) : (
<div className="Auth-form-container">
<form className="Auth-form" >
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Not registered yet?{" "}
<span className="link-primary" onClick={changeAuthMode} >
Sign Up
</span>
</div>
<div className="form-group mt-3">
<label>Username </label>
<input
className="form-control mt-1"
id='userName'
ref={userRef}
name="userName"
value={userName}
placeholder="username"
onChange={(e) => setUserName(e.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Password</label>
<input
className="form-control mt-1"
name="password"
type="password"
id='password'
value={password}
placeholder="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button
type="submit"
className="btn btn-primary"
onClick={(e) => handleLogin(e)}
>
Logga in
</button>
<p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
</div>
</div>
</form>
</div>
)}</>
)
}
// "Register page"
return (
<div className="Auth-form-container">
<form className="Auth-form" onSubmit={(e) => handleRegister(e)}>
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Already registered?{" "}
<span className="link-primary" onClick={changeAuthMode}>
Go to Sign In
</span>
</div>
<div className="form-group mt-3">
<label>Register Your Username here</label>
<input
className="form-control mt-1"
name="userName"
value={userName}
placeholder="ure username here:"
onChange={(event) => setUserName(event.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Register Youre password</label>
<input
className="form-control mt-1"
type="password"
name="password"
value={password}
placeholder="ure password here"
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button type="submit" className="btn btn-primary" onClick={handleRegister}>
Registera
</button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Now Registered Successfully</p>
) : (
<p className="text-danger">Please register your account here</p>
)}
</div>
</div>
</form>
</div>
);
}

Parsing error: 'return' outside of function

I've recently started maintaining JavaScript code and now i am facing trouble in the returning function in line 39. Can someone please help? I have checked the syntax and can't find anything wrong................................................................???????????????????????????????????????????????????????????????????????
import React, { useState, useEffect} from "react";
import axios from "axios";
import { renderMatches, useNavigate, useParams, } from "react-router-dom";
const Editorg = () => {
let navigate = useNavigate();
const {id} = useParams();
console.log(id);
const [user, setUser] = useState ({
name:"",
poname:"",
type:"",
ostatus:"",
});
const { name, poname, type, ostatus } = user;
const onInputChange = e => {
setUser({...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
};
const onSubmit = async e => {
e.preventDefault();
await axios.put( 'http://localhost:3001/users/${id}' , user);
navigate.push("/");
};
const loadUser = async () =>{
const result = await axios.get('http://localhost:3001/users/${id}', user);
setUser(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h5 className="text-left mb-4"> Edit Organization </h5>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<label> Organization Name </label>
<input type="text" className="form-control" name="name" value={name}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Parent Organization Name </label>
<input type="text" className="form-control" name="poname" value={poname}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Type </label>
<input type="text" className="form-control" name="type" value={type}
onChange={e => onInputChange(e)}
/></div>
<div className="form-group">
<label> Organization Status </label>
<input type="text" className="form-control" name="ostatus" value={ostatus}
onChange={e => onInputChange(e)}
/></div>
<div className="container">
<div className="btn-6">
<button className="btn btn-danger float-right">Update</button>
</div>
</div>
</form>
</div>
</div>
);
}
Around line 26 you are closing the function too early.
useEffect(() => {
loadUser();
}, []);
}; // <- Move this to the very end
const onSubmit = async e => {
</div>
</div>
);
}; // <- Move to here
You mistakly add extra termination of curly bracket
useEffect(() => {
loadUser();
}, []);
}; // <--- remove this

react props and events

staffForm.js
import React from 'react'
import { Link } from 'react-router-dom';
const StaffForm = ({handleSubmit},props) => {
// console.log(props);
const title = props.title;
const link =props.link;
return (
<section>
<div class="Employewrapper">
<div class="title">
{title} registration
</div>
<form class="form" onSubmit={handleSubmit} encType='multipart/form-data'>
<div class="inputfield">
<label>First Name</label>
<input required type="text" class="input" name='first_name'/>
</div>
<div class="inputfield">
<label>Last Name</label>
<input required type="text" class="input" name='last_name'/>
</div>
<div class="inputfield">
<label>Email</label>
<input required type="email" class="input" name='email'/>
</div>
<div class="inputfield">
<label>Password</label>
<input required type="password" class="input" name='password'/>
</div>
<div class="inputfield">
<label>Confirm password</label>
<input required type="password" class="input" name='confirm_password'/>
</div>
<div class="inputfield">
<label>Phone</label>
<input required type="tel" class="input" name='phone'/>
</div>
<div class="inputfield">
<label for="file">Profile Picture</label>
<input required type="file" id="file" accept="image/*" class="input" name='profile_picture'/>
</div>
<div class="inputfield">
<label>Birthdate</label>
<input required type="date" class="input" name='birthdate'/>
</div>
<div class="inputfield">
<label for="file">Id Card</label>
<input required type="file" id="file" accept="image/*" class="input" name='identification_card'/>
</div>
<div class="inputfield">
<input required type="submit" class="btn" />
</div>
<Link to={link} className='btn'>Back {title}</Link>
</form>
</div>
</section>
)
}
export default StaffForm;
DeliveryForm.js
import React from 'react'
import { Link } from 'react-router-dom';
import axios from 'axios';
import StaffForm from '../../Components/StaffForm';
import "../../Assets/styles/button.css"
const DeliveryForm = () => {
const url = 'http://127.0.0.1:8000/staff/delivery/';
const handleSubmit = (event)=>{
event.preventDefault();
const data = {
"user": {
"first_name": event.target.first_name.value,
"last_name": event.target.last_name.value,
"email": event.target.email.value,
"password": event.target.password.value,
"confirm_password": event.target.confirm_password.value,
"phone": event.target.phone.value
},
"profile_picture": event.target.profile_picture.files[0],
"birthdate": event.target.birthdate.value,
"identification_card": event.target.identification_card.files[0]
}
axios.request({
method: 'post',
headers: {
"Content-Type": "multipart/form-data",
},
url,
data
}).then(res => {
console.log(res)
})
}
return (
<>
<StaffForm handleSubmit={handleSubmit} title="Delivery" link="/Delivery"/>
</>
)
}
export default DeliveryForm
i have a particular form which i will be using for 3 api's the only difference are the title an the link i know the conventional way of writing props but it seems it not working in this case. on my page its not rendering anything but when i remove the props it works. i tried swithing the position of the props and the {handleSubmit}, when doing that i can see the prop but i can't post.
Just do it as you did with previous things in props.
const StaffForm = (props) => {
const handleSubmit = props.handleSubmit;
const title = props.title;
const link = props.link;
Or you will need to deconstruct everything in one place.
const StaffForm = ({ handleSubmit, title, link }) => {
Why: because props object is the first parameter, always. In my example you deconstruct it, and in your code - you deconstruct only handleSubmit from it and somewhy you were expecting to get a second parameter which you named props. No, only one and only first parameter is your props object.
Additionaly, you can use
const StaffForm = (props) => {
const { handleSubmit, title, link } = props;
or
// Spread operator
const StaffForm = ({handleSubmit, ...props}) => {
const { title, link } = props;

How to Display Selected gif in react js?

I am stuck with a problem , I don't know how to do it. I want to display selected gifs , when I search its work properly , when I click on any gifs only this gifs is selected and display when I click on post button..
In This problem if anyone have any query please free feel to ask
App.js
This is the App.js file only single file I wrote my all code.
import "./App.css";
import { useEffect, useState } from "react";
import Axios from 'axios';
function App() {
const Api_key="QlYtlejKAxArXXXXXXXXXXXXXXXXX";
const Base_Url = "http://api.giphy.com/v1/gifs/search";
const [searchText,setSearchText] = useState("");
const [searchGif,setSearchGif] = useState("");
const [addText,setAddText] = useState([]);
const [gifs,setGifs] = useState([]);
const postValue = ()=>{
const addData = {
id:Date.now(),
name:searchText
}
console.log(addData);
setAddText([...addText,addData])
setSearchText("");
// Add Gifs
gifResponse();
}
const gifResponse = async()=>{
const response = await Axios.get(`${Base_Url}?api_key=${Api_key}&q=${searchGif}`)
// const res = await response.json();
setGifs(response.data.data);
console.log(response.data.data)
}
return (
<div className="App">
<div className="container">
<textarea
type="text"
className="form-control shadow-none mt-3"
rows="15"
cols="50"
placeholder="Write Something Here..."
value={searchText}
onChange={(e)=>setSearchText(e.target.value)}
/>
<div class="input-group mb-3 mt-2">
<input
type="text"
class="form-control shadow-none"
placeholder="Search Gif..."
aria-label="Recipient's username"
aria-describedby="basic-addon2"
value={searchGif}
onChange={(e)=>setSearchGif(e.target.value)}
/>
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2" onClick={postValue}>
POST
</span>
</div>
</div>
{
addText.map((add,index)=>{
return <h4 key={index}>{add.name}</h4>
})
}
{
gifs.map((gif)=>{
return <img src={gif.images.fixed_height.url} />
})
}
</div>
</div>
);
}
export default App;

ReactJs: Get data from parent URL and pass it to child component

I am sending a form data from a form in reactjs. Some pre inputs from the user have to be sent altogether with the form. I get that data from the URL of the parent file and the form is in the child component.
Parent url:
http://localhost:3000/uploadlist?phmcy=2
I have to get the phmcy value from the URL. (Here the data have to be passed is '2').
parent component:
import Upload froimportm './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';
export default function Uploadlist() {
let phmcy = (new URLSearchParams(window.location.search)).get("phmcy")
var myphmcy = JSON.stringify(phmcy);
//const phmcyvalue = new URLSearchParams(this.props.location.search);
//const phmcy = phmcyvalue.get('phmcy')
console.log(myphmcy);
const ordersAPI= (url='https://localhost:44357/api/Orders') => {
return {
fetchAll: () => axios.get(url),
create: newRecord => axios.post(url, newRecord),
update: (id, updateRecord) => axios.put(url + id, updateRecord),
delete: id => axios.delete(url+id)
}
}
const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}
return (
<div className="row">
<div className="jumbotron jumbotron-fluid py-4 "></div>
<div className="container text">
<h1 className="display-4"> Order Register</h1>
</div>
<div className="col-md-4 offset-3">
<Upload
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
Child component: (This is where the form is. I have only included a part)
import React, {useState, useEffect} from 'react';
import myphmcy from './Uploadlist';
//const myphmcy = JSON.stringify(phmcy);
console.log(myphmcy);
const defaultImageSrc = '/images/7.jpg';
const initialFieldValues ={
orderId:0,
dateTime:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customerId:1,
pharmacyId:myphmcy,//data obtaind from the URL have to posted as the pharmacyID when posting.
imageName:'',
imageSrc:'',
imageFile: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageFile = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageFile,
imageSrc : x.target.result
})
}
reader.readAsDataURL(imageFile)
}
else{
setValues({
...values,
imageFile:null,
imageSrc:''
})
}
}
const validate = () => {
let temp = {}
temp.customerName = values.customerName == "" ? false : true;
setErrors(temp)
return Object.values(temp).every(x => x == true)
}
const resetForm = () => {
setValues(initialFieldValues)
document.getElementById('image-uploader').value = null;
}
const handleFormSubmit = e => {
e.preventDefault()
if (validate()){
const formData = new FormData()
formData.append('orderId',values.orderId)
formData.append('dateTime',values.dateTime)
formData.append('status',values.status)
formData.append('status2',values.status2)
formData.append('pharmacyName',values.pharmacyName)
formData.append('customerName',values.customerName)
formData.append('patientName',values.patientName)
formData.append('patientAge',values.patientAge)
formData.append('address',values.address)
formData.append('email',values.email)
formData.append('teleNo',values.teleNo)
formData.append('customerId',values.customerId)
formData.append('pharmacyId',values.pharmacyId)
formData.append('imageName',values.imageName)
formData.append('imageFile',values.imageFile)
addOrEdit(formData, resetForm)
alert("Your file is being uploaded!")
}
}
const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')
return (
<>
<div className="container text-center ">
<p className="lead"></p>
</div>
<form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
<div className="card">
<div className="card-header text-center">Place Your Order Here</div>
<img src={values.imageSrc} className="card-img-top"/>
<div className="card-body">
<div className="form-group">
<input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/>
</div>
<div className="form-group">
<input type="datetime-local" className="form-control" placeholder="Date Time" name="dateTime" value={values.dateTime}
onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className={"form-control" + applyErrorClass('customerName')} placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
</div>
<div className="form-group text-center">
<button type="submit" className="btn btn-light">submit</button>
</div>
</div>
</div>
</form>
</>
)
}
This doesn't work well and I can't post the data. Can some genius help me with this?
Issue
For some reason you import the Uploadlist (the default export/import) and name it myphmcy, save this in the initial state, and then never consume the passed myphmcy prop. This pattern tends to lead to stale state as you need to also handle when the prop values update so you can synchronize the state value.
Solution
Storing passed props is anti-pattern in React, just consume the myphmcy prop directly in the handleFormSubmit submit handler. This ensure you are always using the latest myphmcy props value when submitting the form data.
const handleFormSubmit = e => {
e.preventDefault();
if (validate()) {
const formData = new FormData();
formData.append('orderId', values.orderId);
formData.append('dateTime', values.dateTime);
formData.append('status', values.status);
formData.append('status2', values.status2);
formData.append('pharmacyName', values.pharmacyName);
formData.append('customerName', values.customerName);
formData.append('patientName', values.patientName);
formData.append('patientAge', values.patientAge);
formData.append('address', values.address);
formData.append('email', values.email);
formData.append('teleNo', values.teleNo);
formData.append('customerId', values.customerId);
formData.append('pharmacyId', myphmcy) // <-- use the prop directly
formData.append('imageName', values.imageName);
formData.append('imageFile', values.imageFile);
addOrEdit(formData, resetForm) ;
alert("Your file is being uploaded!");
};
You are getting the myphmcy value from props but setting it outside of the function. So it will set only undefined to the pharmacyId. You need to assign the myphmcy value inside the fnuction.

Categories