Rendering content in react js on submit button - reactjs

I'm fetching content from external api using axios and react hooks.
Currently, I'm rendering {renderedResults} without any button. But I want to add submit button and then only render the results when someone clicks on it.
How to implement it in this scenario?
I tried official doc..but no success...
import React, { useEffect, useState } from "react";
import axios from "axios";
import "./Search.css";
const Search = () => {
const [vpincode, setvPincode] = useState("");
const [vdate, setvDate] = useState("");
const [results, setResults] = useState([]);
useEffect(() => {
const search = async () => {
const { data } = await axios.get("https://api", {
params: {
pincode: vpincode,
date: vdate,
},
});
setResults(data.sessions);
};
search();
}, [vpincode, vdate]);
const renderedResults = results.map((result) => {
return (
<div>
{result.name}
{result.address}
</div>
);
});
return (
<div className="container">
<div className="w-25 mb-3">
<label className="form-label ">Enter Pincode:</label>
<input
value={vpincode}
type="text"
className="form-control"
placeholder="Pincode"
onChange={(e) => setvPincode(e.target.value)}
></input>
</div>
<div className="w-25 mb-3">
<label className="form-label">Date:</label>
<input
value={vdate}
type="text"
className="form-control"
placeholder="Date"
onChange={(e) => setvDate(e.target.value)}
></input>
</div>
{renderedResults}
</div>
);
};
export default Search;

Code not tested, but you can do something like this...
import React, { useEffect, useState } from "react";
import axios from "axios";
import "./Search.css";
const Search = () => {
const [vpincode, setvPincode] = useState("");
const [vdate, setvDate] = useState("");
const [results, setResults] = useState([]);
const fetchApiContent = async (_) => {
const { data } = await axios.get("https://api", {
params: {
pincode: vpincode,
date: vdate,
},
});
setResults(data.sessions);
}
const renderedResults = results.map((result) => {
return (
<div>
{result.name}
{result.address}
</div>
);
});
return (
<div className="container">
<div className="w-25 mb-3">
<label className="form-label ">Enter Pincode:</label>
<input
value={vpincode}
type="text"
className="form-control"
placeholder="Pincode"
onChange={(e) => setvPincode(e.target.value)}
></input>
</div>
<div className="w-25 mb-3">
<label className="form-label">Date:</label>
<input
value={vdate}
type="text"
className="form-control"
placeholder="Date"
onChange={(e) => setvDate(e.target.value)}
></input>
</div>
{renderedResults}
<button onClick={fetchApiContent}>Fetch API Content</button>
</div>
);
};
export default Search;

Related

reactjs "TypeError: Cannot read properties of undefined (reading 'params')"

I'am new using reactjs and looks like I am following the old tutorial with old version of react router. So the objectives is when I want to edit the user detail, the form must be filled with data of previous user before update. I've already comunicate with the backend using axios and it worked fine, but the problem is in "id = props.match.params.id". and here is my code:
UserEdit.tsx
import axios from "axios";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { Navigate } 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);
let id: number;
useEffect(() => {
(
async () => {
const response = await axios.get('roles');
setRoles(response.data);
id = props.match.params.id;
const {data} = await axios.get(`users/${id}`);
setFirstName(data.first_name);
setLastName(data.last_name);
setEmail(data.email);
setRoleId(data.role_id);
}
)()
}, []);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await axios.put('users', {
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" id="floatingRole" placeholder="Role" value={role_id} onChange={e => setRoleId(e.target.value)} required>
{roles.map((r: Role) => {
return (
<option key={r.id} value={r.id}>{r.name}</option>
)
})}
</select>
<label htmlFor="floatingRole">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 in this image below, the data isn't show up and get the error message like this
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'params')
I really appreciate if anyone wants to help me solve this problem so I can learn further. Thankyou
In react-router-dom#6 there are no longer "route props", i.e. no location, history (well, now navigate), and no match.
Use the useParams hook to access the route path parameters.
...
import { Navigate, useParams } from "react-router-dom";
...
const UserEdit = (props: any) => {
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);
})();
}, []); // <-- add `id` to dependency array if you need to be responsive
...
return (
...
);
};
It seems like your params not pass correctly .
Maybe you need to get URL parameters by using useParams
like document (https://v5.reactrouter.com/web/example/url-params)
, or check the Router component path format is correct in your React Router version .
In React Router ^v5.3.0 :
<Route path="users/:id/edit" />

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

Is it possible Preload a form with Firestore values?

I have a form that uploads its values to the Firestore database, and would like to use the same component for updating the values, so the question might really be - how to load initial state according to a conditional whether the props are passed?
The form
import Servis from "./funkc/servisni";
import React, { useState } from "react";
export default function ContactUpdate(props) {
//
console.log(props.item);
//
const initialState = {
id: props.item.id,
ime: props.item.Ime,
prezime: props.item.Prezime,
imeError: "",
prezimeError: "",
date: props.item.Datum,
kontakt: props.item.Kontakt,
kontaktError: "",
published: true,
};
const [theItem, setTheItem] = useState(initialState);
const [imeError, setImeError] = useState();
const [prezimeError, setPrezimeError] = useState();
const [message, setMessage] = useState();
const { item } = props;
if (theItem.id !== item.id) {
setTheItem(item);
}
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
};
const updatePublished = (status) => {
Servis.update(theItem.id0, { published: status })
.then(() => {
setTheItem({ ...theItem, published: status });
setMessage("The status was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const updateItem = () => {
let data = {
Ime: theItem.ime,
Prezime: theItem.prezime,
Kontakt: theItem.kontakt,
Datum: theItem.date,
published: true,
};
Servis.update(theItem.id, data)
.then(() => {
setMessage("The tutorial was updated successfully!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id)
.then(() => {
props.refreshList();
})
.catch((e) => {
console.log(e);
});
};
const validate = () => {
let imeError = "";
let kontaktError = "";
if (!theItem.ime) {
imeError = "obavezan unos imena!";
}
if (!theItem.kontakt) {
imeError = "obavezan unos kontakta!";
}
if (kontaktError || imeError) {
this.setState({ kontaktError, imeError });
return false;
}
return true;
};
return (
<div className="container">
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
// id="title"
name="ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Prezime">Prezime</label>
<input
type="text"
className="form-control"
// id="description"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Datum">Datum</label>
<input
type="text"
className="form-control"
// id="description"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="Kontakt">Kontakt</label>
<input
type="text"
className="form-control"
// id="description"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
{theItem.published ? "Published" : "Pending"}
</div>
</form>
{theItem.published ? (
<button onClick={() => updatePublished(false)}>UnPublish</button>
) : (
<button onClick={() => updatePublished(true)}>Publish</button>
)}
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Please click on a Tutorial...</p>
</div>
)}{" "}
</div>
);
}
The component passing the props:
import React, { useState, useEffect } from "react";
import firebase from "./firebase";
import { Link } from "react-router-dom";
export default function FireDetail({ match }) {
console.log(match);
console.log(match.params.id);
const [item, setItem] = useState([]);
const [loading, setLoading] = useState();
const getIt = () => {
setLoading(true);
const docRef = firebase
.firestore()
.collection("polja")
.doc(match.params.id)
.get()
.then((doc) => {
setItem(doc.data());
});
//
console.log(docRef);
//
// const docRef = firebase.firestore().collection("polja").doc("documentId")
//
setLoading(false);
};
useEffect(() => {
getIt();
}, [match]);
if (loading) {
return <h3>samo malo...</h3>;
}
return (
<div className="container">
<div>
{console.log("item: ", item)}
Kontakt: tip - email
<p> {item.Kontakt}</p>
</div>
<div>
<p>Datum rodjenja: {item.Datum}</p>
{item.Prezime} {item.Ime}
</div>
<Link to={`/kontakt/update/${item.id}`}> ajd </Link>
</div>
);
}
Or you might have an alternative idea on how to solve the problem?
indeed it is
export default function ContactUpdate(props) {
const initialState = {
ime: props.item.Ime,
prezime: props.item.Prezime,
datum: props.item.Datum,
kontakt: props.item.Kontakt,
id: props.Id,
};
const [theItem, setTheItem] = useState();
const [message, setMessage] = useState();
useEffect(() => {
setTheItem(props.item);
}, []);
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
console.log(theItem);
};
const updateItem = (theItem) => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
};
console.log(updateItem());
Servis.update(theItem.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};
const deleteItem = () => {
Servis.remove(theItem.id).catch((e) => {
console.log(e);
});
};
return (
<div className="container">
{console.log(("theItem", props, theItem))}
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
<form>
<div className="form-group">
<label htmlFor="ime">Ime</label>
<input
type="text"
className="form-control"
name="Ime"
value={theItem.Ime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="prezime">Prezime</label>
<input
type="text"
className="form-control"
name="Prezime"
value={theItem.Prezime}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="datum">Datum</label>
<input
type="text"
className="form-control"
name="Datum"
value={theItem.Datum}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="kontakt">Kontakt</label>
<input
type="text"
className="form-control"
name="Kontakt"
value={theItem.Kontakt}
onChange={handleInputChange}
/>
</div>
<div className="form-group">
<label>
<strong>Status:</strong>
</label>
</div>
</form>
<button onClick={deleteItem}>Delete</button>
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Odaberi jedan broj...</p>
</div>
)}{" "}
</div>
);
}

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;

Trouble with bootstrap-validate and useState (React)

I'm using bootstrap-validate for my forms, and I'm running into a really weird problem. If I try to use setIsValidEmail in the callback then whenever I type [some-text]#[some-text].com . I can't type anything pass the 'c' in 'com'. It works fine if I leave the callback and just remove setIsValidEmail.
Repo: https://github.com/mlelien/testtest
import React, { useState } from 'react'
import * as bootstrapValidate from 'bootstrap-validate'
window.bootstrapValidate = bootstrapValidate
const SignUp2 = () => {
const [email, setEmail] = useState('')
const [isValidEmail, setIsValidEmail] = useState(false)
const onEmailChange = (e) => {
const newEmail = e.target.value
setEmail(newEmail)
bootstrapValidate('#form-email', 'email:Invalid email', (isValid) => {
setIsValidEmail(isValid)
})
}
return (
<div className="container">
<h3>SIGN UP</h3>
<form>
<div className="form-group">
<label htmlFor="form-email">
Email address
<input
type="email"
className="form-control"
id='form-email'
aria-describedby='enter email'
placeholder='Enter email'
value={email}
onChange={onEmailChange}
/>
</label>
</div>
</form>
</div>
)
}
export default SignUp2

Resources