ReactJS can't make request to ASP.NET Web API - reactjs

I have a React app in front-end with ASP.NET Web Api in back-end. When I try to make a PUT request from React to Web Api in the console appears error with number 400. With all other requests everything is fine. I put a breakpoint in ASP.NET in debug but even then request doesn't get in Web API.
This is my code in React:
import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './editContact.module.css';
const EditContact = () => {
const id = window.location.pathname.slice(14);
const navigate = useNavigate();
const [contactName, setContactName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [description, setDescription] = useState('');
const [categories, setCategories] = useState('');
const [areas, setAreas] = useState('');
const [event, setEvent] = useState('');
const [continent, setContinent] = useState('');
const [country, setCountry] = useState('');
const getContact = useCallback (async () => {
const request = await fetch(`https://localhost:7082/api/contacts/${id}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const response = await request.json();
setContactName(response.name);
setEmail(response.email);
setAreas(response.areas);
setCategories(response.categories);
setDescription(response.description);
setEvent(response.event);
setPhone(response.phoneNumber);
setContinent(response.continent);
setCountry(response.country);
}, [id]);
const sendToHome = () => {
navigate('/');
};
const editContact = async (e) => {
e.preventDefault();
await fetch(`https://localhost:7082/api/contacts/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contactName,
email,
phone,
description,
areas,
event,
categories,
continent,
country
})
})
.then(() => {
navigate('/');
})
.catch((e) => {
alert(e.message);
})
};
useEffect(() => {
getContact();
}, [getContact]);
return (
<form className={styles.form} onSubmit={editContact}>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Name</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setContactName(e.target.value)} value={contactName} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">eMail</label>
<input type="email" className="form-control" id="exampleFormControlInput1" onChange={e => setEmail(e.target.value)} value={email} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Phone</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setPhone(e.target.value)} value={phone} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Description</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setDescription(e.target.value)} value={description} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Categories</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setCategories(e.target.value)} value={categories} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Areas</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setAreas(e.target.value)} value={areas} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Event</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setEvent(e.target.value)} value={event} />
</div>
<button type='submit' className='btn btn-success mt-5' style={{ marginRight: 5 + 'px' }} name='edit'>Submit</button>
<button className='btn btn-secondary mt-5' onClick={sendToHome}>Cancel</button>
</form>
);
};
export default EditContact;
And this is my code in ASP.NET:
[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
private readonly IContactsService contactsService;
public ContactsController(IContactsService contactsService)
{
this.contactsService = contactsService;
}
[HttpGet]
public JsonResult AllContacts()
{
var result = this.contactsService.GetAllContacts();
return new JsonResult(result);
}
[HttpGet("{id}")]
public JsonResult ContactDetails(string id)
{
var result = this.contactsService.GetContactDetails(id);
return new JsonResult(result);
}
[HttpPost]
public ActionResult AddContact(AddContactViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest();
}
this.contactsService.AddContact(model);
return this.Ok();
}
[HttpPut("{id}")]
public ActionResult EditContact(string id, EditContactViewModel model)
{
this.contactsService.EditContact(id, model);
return this.Ok();
}
}
I will happy if someone could help me.

Related

ReactJS select first option doesn't work properly

I have a react app with edit logic with select tag and options for continents and countries. In the continents it seems everything is alright but in countries I can't set a first option. First I must to select another country and then first option is available for set.
This is my code:
import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './editContact.module.css';
import { urls, methods } from '../constants';
import requester from '../services/requester';
import notificationsReceiver from '../services/notificationReceiver';
const EditContact = () => {
const id = window.location.pathname.slice(14);
const navigate = useNavigate();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [description, setDescription] = useState('');
const [categories, setCategories] = useState('');
const [areas, setAreas] = useState('');
const [event, setEvent] = useState('');
const [continentId, setContinent] = useState('');
const [countryId, setCountry] = useState('');
const [continents, setContinents] = useState([]);
const [countries, setCountries] = useState([]);
const getContact = useCallback(async () => {
const request = await requester(urls.contacts + '/' + id, methods.get);
const response = await request.json();
setName(response.name);
setEmail(response.email);
setAreas(response.areas);
setCategories(response.categories);
setDescription(response.description);
setEvent(response.event);
setPhone(response.phoneNumber);
setContinent(response.continentId);
setCountry(response.countryId);
}, [id]);
const sendToHome = () => {
navigate(urls.mainPage);
};
const editContact = async (e) => {
e.preventDefault();
await requester(urls.contacts + '/' + id, methods.put, {
name,
email,
phone,
description,
areas,
event,
categories,
continentId,
countryId
}
)
.then(() => {
navigate(urls.mainPage);
notificationsReceiver('Contact is edited successfully!');
})
.catch((e) => {
alert(e.message);
})
};
const getContinents = async () => {
const request = await requester(urls.getContinents, methods.get);
const response = await request.json();
setContinents(response);
};
const getCountries = async () => {
const request = await requester(urls.getCountries, methods.get);
const response = await request.json();
setCountries(response);
};
useEffect(() => {
getContact();
getContinents();
getCountries();
}, [getContact]);
return (
<form className={styles['edit-form']} onSubmit={editContact}>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Name</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setName(e.target.value)} value={name} />
</div>
<label htmlFor="exampleFormControlInput1">Continent</label>
<select className="form-control" id="exampleFormControlSelect1" title="continent" name="continent" onChange={e => setContinent(e.target.value)} value={continentId}>
{continents.map(continent =>
<option key={continent.continentId} value={continent.continentId}>{continent.continentName}</option>
)}
</select>
<label htmlFor="exampleFormControlInput1">Countries</label>
<select className="form-control" id="exampleFormControlSelect1" title="country" name="country" onChange={e => setCountry(e.target.value)} value={countryId}>
{countries.filter(x => x.placeIsContainedInId === continentId).map(country =>
<option key={country.countryId} value={country.countryId}>{country.countryName}</option>
)}
</select>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">eMail</label>
<input type="email" className="form-control" id="exampleFormControlInput1" onChange={e => setEmail(e.target.value)} value={email} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Phone</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setPhone(e.target.value)} value={phone} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Description</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setDescription(e.target.value)} value={description} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Categories</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setCategories(e.target.value)} value={categories} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Areas</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setAreas(e.target.value)} value={areas} />
</div>
<div className="form-group">
<label htmlFor="exampleFormControlInput1">Event</label>
<input type="text" className="form-control" id="exampleFormControlInput1" onChange={e => setEvent(e.target.value)} value={event} />
</div>
<button type='submit' className='btn btn-success mt-5' style={{ marginRight: 5 + 'px' }} name='edit'>Submit</button>
<button className='btn btn-secondary mt-5' onClick={sendToHome}>Cancel</button>
</form>
);
};
export default EditContact;
If someone knows how to resolve this problem, I'll be grateful.

ReactJS .... map() is not a function

I have a problem with my code. I have a tag with options, when I try to set contact type set contact type appears white screen with error in the console "types.map() is not a function" white screen with errors. I think the problem comes from that at the beginning "types" are array and when I choose contact type with the state() "types" become a single value. I don't know how to fix that.
This is my code:
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from './postContact.module.css';
const PostContact = () => {
const [nickName, setNickName] = useState('');
const [address, setAddress] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [account, setAccount] = useState('');
const [types, setType] = useState([]);
const navigate = useNavigate();
const postContact = async (e) => {
e.preventDefault();
await fetch('http://localhost:5090/api/contacts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
nickName,
address,
phoneNumber,
userId: 1,
contactTypeId: types,
account
})
})
.then(() => {
navigate('/');
})
.catch((e) => {
alert(e.message)
});
};
const getTypes = async () => {
const request = await fetch('http://localhost:5090/api/contactTypes', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const response = await request.json();
setType(response);
};
useEffect(() => {
getTypes();
}, []);
return (
<form className={styles['post-form']} onSubmit={postContact}>
<label htmlFor='nickName'>Nickname</label>
<input className={styles.input} id='nickName' type='text' onChange={e => setNickName(e.target.value)} value={nickName} />
<label htmlFor='address'>Address</label>
<textarea className={styles.input} id='address' type='text' onChange={e => setAddress(e.target.value)} value={address} />
<label htmlFor='phoneNumber'>Phone Number</label>
<input className={styles.input} id='phoneNumber' type='text' onChange={e => setPhoneNumber(e.target.value)} value={phoneNumber} />
<label htmlFor='account'>Account</label>
<input className={styles.input} id='account' type='text' onChange={e => setAccount(e.target.value)} value={account} />
<label htmlFor="type">Contact Type</label>
<select className={styles.input} title="type" name="type" onChange={e => setType(e.target.value)} value={types}>
{types.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>
<button className="btn btn-primary mt-5" type='submit' name='Post'>Create</button>
</form>
);
};
export default PostContact;
I'll be grateful if anyone can help me.
On the first render the value for types will be undefined ( on sync code execution ), try using it as
<select className={styles.input} title="type" name="type" onChange={e => setType(e.target.value)} value={types}>
{types?.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>
? will make sure to run map once value for types is there ( also make sure it is mappable ( is an array ))
Handle the array falsy cases before doing any operations on it
<select
className={styles.input}
title="type" name="type"
onChange={e => setType(e.target.value)}
value={types}
>
{types.length && types.map(type=>
<option key={type.id} value={type.id}>{type.type}</option>
)}
</select>

put method not working with react axios api method

I have this api running on my localhost, using drf. I defined a put method to use to update an object. When i do this in the backend it works, everything gets updated, but when i do it in the frontend nothing gets updated but i get a 200 OK status code. How can i make it work?
Here is my react code:
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router';
import axios from 'axios';
const EkoEditPage = () => {
const [disco, setDisco] = useState("")
const [feederSource33kv, setFeederSource33kv] = useState("")
const [injectionSubstation, setInjectioSubstation] = useState("")
const [feederName, setFeederName] = useState("")
const [band, setBand ] = useState("")
const [status, setStatus] = useState("")
const history = useHistory();
const { id } = useParams();
const loadEkoMyto = async () => {
const { data } = await axios.get(`http://127.0.0.1:8000/main/view/${id}`);
setDisco(data.dicso)
setFeederSource33kv(data.feeder_source_33kv)
setInjectioSubstation(data.injection_substation)
setFeederName(data.feeder_name )
setBand(data.band)
setStatus(data.status)
}
const updateEkoMyto = async () => {
let formField = new FormData()
formField.append('disco', disco)
formField.append('feeder_source_33kv', feederSource33kv)
formField.append('injecttion_substation', injectionSubstation)
formField.append('feeder_name',feederName)
formField.append('band', band)
formField.append('status', status)
await axios({
method: 'PUT',
url: `http://127.0.0.1:8000/main/edit/${id}`,
data: formField
}).then(response => {
console.log(response.data)
})
}
useEffect (() => {
loadEkoMyto()
}, [])
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Update A Student</h2>
<div className="form-group">
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="disco"
value={disco}
onChange={(e) => setDisco(e.target.value)}
/>
</div>
<div className="form-group">
<input
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="feeder_source_33kv"
value={feederSource33kv}
onChange={(e) => setFeederSource33kv(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="injection_substation"
value={injectionSubstation}
onChange={(e) => setInjectioSubstation(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your address Name"
name="address"
value={feederName}
onChange={(e) => setFeederName(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="address"
value={band}
onChange={(e) => setBand(e.target.value)}
/>
</div>
<select name="status" onChange={(e) => setStatus(e.target.value)}>
<option value={status}>Yes</option>
<option value={status}>No</option>
</select>
<button className="btn btn-primary btn-block" onClick={updateEkoMyto}>Update Eko</button>
</div>
</div>
);
};
export default EkoEditPage;
}

Pass multiple variable with POST method in React app

I'm trying to post multiple variables to my Postgres database using a form with React.
This is my current script:
const InputAddress = () => {
const [name, setName] = useState("");
const [problem, setProblem] = useState("");
const [date, setDate] = useState("");
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const body = {
name,
problem,
date,
};
console.log(params);
const response = await fetch("http://localhost:5000/logements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
window.location = "/";
} catch (error) {
console.log(error.message);
}
};
return (
<Fragment>
<h1 className="text-center mt-5">Add your address</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<label>Comment</label>
<input
type="text"
className="form-control"
value={problem}
onChange={(e) => setProblem(e.target.value)}
/>
<label>Date</label>
<input
type="text"
className="form-control"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
</Fragment>
);
};
My problem seems to be with the fetch method.
When I submit the form, I get this error message in the console :
bind message supplies 1 parameters, but prepared statement "" requires 3
Is there a simple fix to this problem?

How to Edit a form in React by using functional components

I am working on a React project, In my project I have a form, In that form I fetch data by Id
From the backend, Now I am trying to do put method. But I have no idea how doing it so please me
How to send edited data to backend using the put method.
This is my code Editstudentdetails.js
import React, { useState, useEffect } from 'react';
import './Editstudentdetails.css';
import axios from 'axios';
import { withRouter } from 'react-router-dom'
function Editstudentdetails(props) {
const [getStudentDataById, setStudentDataById] = useState([])
const [editStudentDataById, latestEdit] = useState({ name:'', position: '', location: '', salary: '', email: '', password: '' })
const id = props.match.params.id
console.log(id)
useEffect(() => {
const getDataById = async () => {
try {
const result = await axios.get(`http://localhost:7500/api/registration/${id}`)
setStudentDataById(result.data)
console.log(result.data)
} catch (error) {
console.log(error)
}
}
getDataById()
}, [])
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, getStudentDataById, { [name]: value });
setStudentDataById(newData);
const latestData = Object.assign({}, editStudentDataById, { [name]: value })
latestEdit(latestData)
}
const handleSubmit = async e => {
e.preventDefault();
console.warn(editStudentDataById)
const editDataById = async () => {
try {
const response = await axios.put(`http://http://localhost:7500/api/registration/${id}`, editStudentDataById)
latestEdit(response.data)
console.warn(response.data)
} catch (error) {
console.warn(error)
}
}
editDataById()
}
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" name='name' value={getStudentDataById.name} onChange={handleChange} className="form-control" id="name"></input>
</div>
<div className="form-group">
<label htmlFor="position">Position</label>
<input type="text" name='position' value={getStudentDataById.position} onChange={handleChange} className="form-control" id="position"></input>
</div>
<div className="form-group">
<label htmlFor="location">Location</label>
<input type="text" name='location' value={getStudentDataById.location} onChange={handleChange} className="form-control" id="location"></input>
</div>
<div className="form-group">
<label htmlFor="salary">Salary</label>
<input type="number" name='salary' value={getStudentDataById.salary} onChange={handleChange} className="form-control" id="salary"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" name='email' onChange={handleChange} value={getStudentDataById.email} className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" name='password' onChange={handleChange} value={getStudentDataById.password} className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default withRouter(Editstudentdetails)
If you feel I am not clear with my doubt please put a comment Thank you
Please follow this example. It works perfectly.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function EditStudentDetails() {
const [post, setPost] = useState({});
const id = 1;
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const editDataById = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
editDataById();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default EditStudentDetails;

Resources