ReactJS select first option doesn't work properly - reactjs

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.

Related

Fields tied to the state doesn't clear on successful form submission

I have a contact form, when the form submission is successful it should clear the form field name, email and message which is tied up to the state. The form submission is successful but form fields name, email and message doesn't clear.
For test purpose what I'm doing is passing default values to the state but this values doesn't get filled in form during initial load.
export default function Contact() {
const [name, setName] = useState('John Doe')
const [email, setEmail] = useState('me#example.com')
const [message, setMessage] = useState('Hello, this is test message.')
const onSubmit = (e) => {
e.preventDefault()
const form = {"name": name, "email": email, "message": message}
return fetch('/api/contact', {
method: 'POST',
body: JSON.stringify(form),
headers: {'Content-Type': 'application/json'}
}).then(response => {
if(response.status === 200){
setName('')
setEmail('')
setMessage('')
} else {
}
}).catch(err => err)
}
return (
<section>
<form method='post'>
<div>
<label>Name</label>
<input type="text" name="name" onChange={(e) => {setName(e.target.value)}}/>
</div>
<div>
<label>Email Address</label>
<input type="email" name="email" onChange={(e) => {setEmail(e.target.value)}}/>
</div>
<div>
<label>Message</label>
<textarea minLength={5} maxLength={2000} rows="6" name="message" onChange={(e) => {setMessage(e.target.value)}}></textarea>
</div>
<div>
<button type='submit' onClick={(e) => {onSubmit(e)}}>Send Message</button>
</div>
</form>
</section>
);
}
As User456 said, you need to add value={variable} for every <input />.
Example:
import { useState } from "react";
export default function Contact() {
const [name, setName] = useState("John Doe");
const [email, setEmail] = useState("me#example.com");
const [message, setMessage] = useState("Hello, this is test message.");
const onSubmit = (e: any) => {
e.preventDefault();
setName("");
setEmail("");
setMessage("");
};
return (
<section>
<form method="post">
<div>
<label>Name</label>
<input
type="text"
name="name"
value={name}
onChange={e => {
setName(e.target.value);
}}
/>
</div>
<div>
<label>Email Address</label>
<input
type="email"
name="email"
value={email}
onChange={e => {
setEmail(e.target.value);
}}
/>
</div>
<div>
<label>Message</label>
<textarea
minLength={5}
maxLength={2000}
name="message"
value={message}
onChange={e => {
setMessage(e.target.value);
}}></textarea>
</div>
<div>
<button
type="submit"
onClick={e => {
onSubmit(e);
}}>
Send Message
</button>
</div>
</form>
</section>
);
}

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

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.

Can't type in textarea when displayed

import React, { useState } from 'react'
const FormBox = () => {
const [name, setName] = useState("")
const [textArea, setTextArea] = useState('')
const handleSumbit = (e) =>{
e.preventDefault();
console.log(name)
}
return (
<form onSubmit={handleSumbit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<textarea value={textArea} onChange={handleSumbit}></textarea>
<input type="submit" />
</form>
)
}
When the text box is displayed I cannot type in it.
What am I doing wrong...?
import React, { useState } from 'react'
const FormBox = () => {
const [name, setName] = useState('')
const [textArea, setTextArea] = useState('')
const handleSumbit = (e) =>{
e.preventDefault();
console.log(name)
}
return (
<form onSubmit={handleSumbit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
<input type="submit" />
</form>
)
}
The textarea is a controlled input - if you are going to tie the value of the <textarea> to the textArea state variable, you need to update that state variable whenever the user changes the input.
Shouldn't the onChange={handleSumbit} of the textarea be
onChange={(e) => setTextArea(e.target.value)}
import React, { useState } from 'react'
const FormBox = () => {
const [name, setName] = useState("")
const [textArea, setTextArea] = useState('')
const handleSumbit = (e) =>{
e.preventDefault();
console.log(name)
}
return (
<form onSubmit={handleSumbit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setTextArea(e.target.value)}
/>
</label>
<textarea value={textArea} onChange={handleSumbit}></textarea>
<input type="submit" />
</form>
)
}
Firstly
You implicitly set the value of your text area using the textArea variable which has an initial state of "" (an empty string).
React automatically refreshes the real DOM from the virtual DOM after every change in state. But the value of your textArea variable doesn't change with this event, so you have to update the state when a value is entered like this:
onChange={(e) => setTextArea(e.target.value)}
After reading your code, I guessed what you wanted to achieve is to prevent the submit button from submitting the form by default and instead logs the name on the console.
I believe this is the code you wanted to achieve:
import React, { useState } from 'react'
const FormBox = () => {
const [name, setName] = useState('')
const [textArea, setTextArea] = useState('')
const handleSumbit = (e) =>{
e.preventDefault();
console.log(name)
}
return (
<form onSubmit={handleSumbit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
<input type="submit" />
</form>
)
You can't type here the event not written by you properly, so, you state textarea not updated yet. just needed to change one as a similar name textbox. just replace
<textarea value={textArea} onChange={handleSumbit}></textarea>
to
<textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
Full code here edited,
import React, { useState } from 'react'
const FormBox = () => {
const [name, setName] = useState('')
const [textArea, setTextArea] = useState('')
const handleSumbit = (e) =>{
e.preventDefault();
// console here form data
}
return (
<form onSubmit={(e)=>handleSumbit(e)}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<textarea value={textArea} onChange={(e) => setTextArea(e.target.value)}></textarea>
<input type="submit" value="Submit now!" />
</form>
)
I Hope, work fine using this code
Thanks

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;
}

Data Fetching with React using useEffect

What I am trying to do is when the user click the edit button, this will send him to a new page where he can modify the info he already entered. The problem I am facing is that the new page is not showing the data previously entered, so that the user can make his changes. Also, the submit button to send those changes is not working. These are the errors I am getting: src\components\RestaurantList.jsx
Line 25:8: React Hook useEffect has a missing dependency: 'setRestaurants'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Line 31:19: 'response' is assigned a value but never used no-unused-vars
src\components\UpdateRestaurant.jsx
Line 9:12: 'restaurants' is assigned a value but never used no-unused-vars
Line 38:8: React Hook useEffect has a missing dependency: 'code'. Either include it or remove the dependency array react-hooks/exhaustive-deps
My code for the component I am working on:
import React, {useState, useContext, useEffect} from 'react';
import { useHistory, useParams } from 'react-router-dom';
import RestaurantFinder from '../apis/RestaurantFinder';
import { RestaurantsContext } from '../context/RestaurantsContext';
const UpdateRestaurant = (props) => {
const {code} = useParams();
const {restaurants} = useContext(RestaurantsContext);
let history = useHistory();
const [name, setName] = useState("");
const [value, setValue] = useState ("");
const [strain, setStrain] = useState ("");
const [weight, setWeight] = useState ("");
const [authors, setAuthors] = useState ("");
const [number, setNumber] = useState ("");
const [page, setPage] = useState ("");
const [date, setDate] = useState ("");
useEffect(() => {
const fetchData = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setName(response.data.data.restaurant.name);
setValue(response.data.data.restaurant.value);
setStrain(response.data.data.restaurant.strain);
setWeight(response.data.data.restaurant.weight);
setAuthors(response.data.data.restaurant.authors);
setNumber(response.data.data.restaurant.number);
setPage(response.data.data.restaurant.page);
setDate(response.data.data.restaurant.date);
};
fetchData();
}, []);
const handleSubmit = async(e) => {
e.preventDefault();
const updatedRestaurant = await RestaurantFinder.put(`/${code}`, {
name,
value,
strain,
weight,
authors,
number,
page,
date,
});
console.log(updatedRestaurant);
history.push("/");
};
return (
<div>
<form action="">
<div className="form-group">
<label htmlFor="name">Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} code="name" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Value">Value</label>
<input value={value} onChange={(e) => setValue(e.target.value)} code="value" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Strain">Strain</label>
<input value={strain} onChange={(e) => setStrain(e.target.value)} code="strain" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Weight">Weight</label>
<input value={weight} onChange={(e) => setWeight(e.target.value)} code="weight" className="form-control" type="float" />
</div>
<div className="form-group">
<label htmlFor="Author">Author</label>
<input value={authors} onChange={(e) => setAuthors(e.target.value)} code="authors" className="form-control" type="text" />
</div>
<div className="form-group">
<label htmlFor="Number">Number</label>
<input value={number} onChange={(e) => setNumber(e.target.value)} code="number" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="Page">Page</label>
<input value={page} onChange={(e) => setPage(e.target.value)} code="page" className="form-control" type="number" />
</div>
<div className="form-group">
<label htmlFor="date">Date</label>
<input value={date} onChange={(e) => setDate(e.target.value)} code="date" className="form-control" type="number" />
</div>
<button onClick={handleSubmit} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
)
}
export default UpdateRestaurant
for reusable code, it may be best to just do something like this.
This is probably not the answer, but I hope it helps you find out the answer.
const [data, setData ] = useState({restraunt.loaded:"false"});
useEffect(() => {
const fetch = async () => {
const response = await RestaurantFinder.get(`/${code}`);
console.log(response.data.data);
setData({...response.data.data, restraunt.loaded:"true"});
};
fetch();
},[Data.restraunt.loaded])
const {name, value , page, loaded } = Data.restaurant;
return (
<div><h1>{loaded}</h1>
</div>
)
If it shows loaded as false then you know it is because of the data not loading.

Resources