This is for api re-rendering issue, I want to know that how to call one api after selecting a dropdown option.
Here it re-render infinite time after selecting an-option in drop-down. I call an client Api from client collection and show in client drop down after I select drop down and going to the infinite loop.
import Select from "react-select";
import Axios from "axios";
import React, { useState, useEffect } from "react";
export default function Form() {
const [hday, setHday] = useState(null);
const [date, setDate] = useState(null);
const [hdata, setHdata] = useState([]);
const [hid, setHid] = useState(""); //changed use state value null to []
const [client, setClient] = useState([]);
const [clientvalue, setClientValue] = useState(null);
const [clientId, setClientId] = useState(""); //changed use state value null to []
const [cemail, setCemail] = useState([]);
const [clientname, setClientname] = useState(null);
const [clientEmail, setClientEmail] = useState([]);
const [message, setMessage] = useState("");
const [fromField, setFromField] = useState("");
const [loading, setLoading] = useState(false);
const handleRequest = async (e) => {
if (clientvalue && hday && fromField && cemail && clientEmail && message !== "") {
if (message !== "") {
e.preventDefault();
setLoading(true);
console.log({
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
});
const body = {
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
};
await Axios.post("http://localhost:3002/mail", body, {
headers: {
"Content-type": "application/json",
},
})
.then((res) => {
alert("Email Sent Successfully");
setLoading(false);
console.log(res);
window.location.reload();
})
.catch((err) => {
console.log(err);
setLoading(false);
});
} else {
alert("Compose Email");
}
} else {
alert("Please fill all required filled");
}
};
const fromFieldChange = (obj) => {
setFromField(obj.target.value);
};
const handleQuillChange = (e) => {
setMessage(e.target.value);
};
function handleHolidayChange(obj) {
console.log("This is object country", obj);
setHday(obj);
setHid(obj._id);
setDate(null);
}
//client call (repetadely call)
const onChangeClient = (obj) => {
console.log("client object", obj);
console.log("client object id", obj._id);
setClientValue(obj);
setClientId(obj._id);
setClientname(obj.client_name);
};
// console.log("This is client id and name", clientId + " " + clientname);
//(issues repetadely execute)
async function emailClick() {
const url = `http://localhost:3002/api/getClientEmail/${clientId}/${clientname}`;
Axios.get(url)
.then((response) => {
const temp = response.data.map((e) => e.email);
setCemail(temp);
console.log("Client Email", cemail);
})
.catch((error) => {
console.log(error);
});
}
emailClick();
const changeDate = async function dateClick() {
const url = `http://localhost:3002/api/holiday_date/${hid}`;
await Axios.get(url)
.then((response) => {
// console.log("This is holiday date",response.data[0]['date_of_holiday']);
setDate(response.data.date_of_holiday);
// console.log("holiday year",date);
})
.catch((error) => {
console.log(error);
});
};
changeDate();
useEffect(
() => {
async function getHoliday() {
const url = `http://localhost:3002/api/holidays`;
await Axios.get(url)
.then((response) => {
setHdata(response.data);
console.log("this is holiday", response.data);
})
.catch((err) => {
console.log(err);
});
}
getHoliday();
async function getClient() {
const url = `http://localhost:3002/api/client`;
await Axios.get(url)
.then((response) => {
setClient(response.data);
console.log("this is client", response.data);
})
.catch((err) => {
console.log(err);
});
}
getClient();
///api/emailtemplates
async function getClientEmail() {
const url = `http://localhost:3002/api/emailtemplates`;
await Axios.get(url)
.then((response) => {
setClientEmail(response.data.map((e) => e.subject));
})
.catch((err) => {
console.log(err);
});
}
getClientEmail();
},
[date],
[cemail],
);
return (
<form onSubmit={handleRequest} method="post">
<div className="form">
<div className="form__wrapper">
<div className="form__title">
{/* title */}
<h4>Holiday</h4>
</div>
<div className="form__container">
<div className="form__containerItems">
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Client</label>
</div>
<div className="form__containerItemField">
<Select
onChange={onChangeClient}
placeholder="Select Client"
value={clientvalue}
options={client}
getOptionLabel={(x) => x.client_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Holiday</label>
</div>
<div className="form__containerItemField">
<Select
onChange={handleHolidayChange}
placeholder="Select Holiday"
value={hday}
options={hdata}
getOptionLabel={(x) => x.holiday_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Date</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="date..." defaultValue={date} />
</div>
</div>
</div>
</div>
<div className="form__container">
<div className="form__containerItems">
{/* from */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>From</label>
</div>
<div className="form__containerItemField">
<input
type="email"
placeholder="Sender Email.."
// autoFocus="autoFocus"
value={fromField}
onChange={fromFieldChange}
/>
</div>
</div>
{/* to */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>To</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Client Emial.." defaultValue={cemail} />
</div>
</div>
{/* Subject */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Subject</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Write your Sub..." defaultValue={clientEmail} />
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Compose Mail</label>
<button
disabled={loading}
onClick={handleRequest}
type="submit"
className="btn btn-info"
>
Send
</button>
</div>
</div>
<div className="form__containerItem">
<div className="container__composeMail">
<textarea
value={message}
onChange={handleQuillChange}
className="quill"
placeholder="Enter Content from here..."
/>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
);
}
Related
https://hapi.fhir.org/baseR4/Patient I want to do a get post and delete operation with axios from this api. While performing the get operation successfully, I am getting errors in the delete and post operation.Actually, I think I've solved some of the problem, because the api I got is not an object, I'm getting these errors probably, but I don't know how to convert an api to an object or I don't have the slightest idea how to use the object function, please help me
const client = axios.create({
baseURL: "https://hapi.fhir.org/baseR4/Patient",
});
const App = () => {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [patients, setPosts] = useState([]);
// GET with Axios
useEffect(() => {
const fetchPost = async () => {
try {
let response = await client.get("?_limit=10");
setPosts(response.data);
} catch (error) {
console.log(error);
}
};
fetchPost();
}, []);
// DELETE with Axios
const deletePost = async (id) => {
try {
await client.delete(`${id}`);
setPosts(
patients.filter((post) => {
return post.id !== id;
})
);
} catch (error) {
console.log(error);
}
};
// handle form submission
const handleSubmit = (e) => {
e.preventDefault();
addPosts(title, body);
};
// POST with Axios
const addPosts = async (title, body) => {
try {
let response = await client.post("", {
title: title,
body: body,
});
setPosts([response.data, ...patients]);
setTitle("");
setBody("");
} catch (error) {
console.log(error);
}
};
return (
<div className="app">
<nav>
<h1>POSTS APP</h1>
</nav>
<div className="add-post-container">
<form onSubmit={handleSubmit}>
<input
type="text"
className="form-control"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
name=""
className="form-control"
id=""
cols="10"
rows="8"
value={body}
onChange={(e) => setBody(e.target.value)}
></textarea>
<button type="submit">Add Post</button>
</form>
</div>
<div className="patients-container">
<h2>All Posts 📫</h2>
{patients?.entry?.map((patient) => (
<div className="patient-card" key={patient.id}>
{patient?.resource?.address?.map((adr) => {
return (
<>
<p>{adr.city}</p>
<p>{adr.postalCode}</p>
</>
);
})}
<div className="button">
<button
className="delete-btn"
onClick={() => deletePost(patient.id)}
>
Delete
</button>
</div>
</div>
))}
</div>
</div>
);
};
export default App;
This is the error I get while doing the delete operation: TypeError: patients.filter is not a function at deletePost (Patient.js:31:1) This is the error I get while doing the add operation POST hapi.fhir.org/baseR4/Patient 400 (Bad Request) AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST' –
I want to create multiple dynamic fields for searching (so I can add or subtract text fields to write the search), here's my code on the backend to find the requestor and the frontend which is still not integrated with the backend (I still following the tutorial steps to create a form whose fields are dynamic)
how do I get the two parts to be properly integrated and can produce data search results when pressing the handlesubmit button?
here I use react JS, node JS, express, and MySQL
thanks
for backend
export const getRequestor = async (req: TypedRequestQuery<{lastId: string, search_requestor:string}>, res: Response) =>{
const searchRequestor = req.query.search_requestor || "";
const resultRequestor = await Product.findAll({
where:{
[Op.or]: [
{title_dev:{ //requestor
[Op.like]: '%'+searchRequestor+'%'
}}]
},
order:[
['id_project', 'ASC']
]
});
res.json({
resultRequestor: resultRequestor,
});
}
for frontend
const Audit = () => {
const [requestors, setRequestors] = useState([]);
const [keyword, setKeyword] = useState("");
const [query, setQuery] = useState("");
useEffect(() => {
getRequestor();
}, [keyword]);
const getRequestor = async () => {
const response = await axios.get(
`http://localhost:5001/requestor?search_requestor=${keyword}`
);
setRequestors(response.data.resultRequestor);
};
const [inputFieldsRequestor, setInputFieldsRequestor] = useState([
{idRequestor: uuidv4(), requestor: ''},
]);
const handleSubmitRequestor = (e) => {
e.preventDefault();
console.log("InputFieldsRequestor", inputFieldsRequestor);
};
const handleSubmitAll = (e) => {
e.preventDefault();
console.log("InputFieldsRequestor", inputFieldsRequestor);
console.log("InputFieldsPeriod", inputFieldsPeriod);
};
const handleChangeInputRequestor = (idRequestor, event) => {
const newInputFieldsRequestor = inputFieldsRequestor.map(i => {
if(idRequestor === i.idRequestor){
i[event.target.name] = event.target.value
}
return i;
})
setInputFieldsRequestor(newInputFieldsRequestor);
}
const handleAddFieldsRequestor = () =>{
setInputFieldsRequestor([...inputFieldsRequestor, {idRequestor: uuidv4(), requestor:''}])
// setRequestors([...requestors]);
}
const handleRemoveFieldsRequestor = idRequestor => {
const values = [...inputFieldsRequestor];
values.splice(values.findIndex(value => value.idRequestor === idRequestor), 1);
setInputFieldsRequestor(values);
}
const submitrequestor= (e) =>{
e.preventDefault();
setKeyword(query);
console.log("Requestor", requestors);
}
return(
<div>
<form className='form-horizontal' onSubmit={handleSubmitRequestor}>
{inputFieldsRequestor.map(inputFieldRequestor => (
<div key={inputFieldRequestor.idRequestor}>
<div className="form-group row">
<label className="col-sm-2 col-form-label">Requestor</label>
<div className="col-sm-10">
<input type="text"
name="requestor"
className="form-control"
variant="filled"
value={inputFieldRequestor.requestor}
onChange={event => handleChangeInputRequestor(inputFieldRequestor.idRequestor, event)}
placeholder="Requestor" />
<button className="offset-sm-1 col-sm-2" disabled={inputFieldsRequestor.length === 1}
onClick={() => handleRemoveFieldsRequestor(inputFieldRequestor.idRequestor)}>
-
</button >
<button className="offset-sm-1 col-sm-2" onClick={handleAddFieldsRequestor}>
+
</button>
</div>
</div>
</div>
))}
<button
className="btn btn-danger"
type='submit'
onClick={handleSubmitRequestor}
>
send
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>)}
My projct is a note app where you can can add notes and delete notes. I want to get data from the database and show it but I have to delete note twice, add note or reload page to show the new data.
notesList.jsx
this is my main component
i send getNotes() to another component for i can get new datas
const NotesList = () => {
const [notes, setNotes] = useState([]);
const getNotes = async () => {
const getNoteInformation = {
email: localStorage.getItem("tokenEmail"),
};
const response = await axios.post(
"http://localhost:9000/api/note/get",
getNoteInformation
);
try {
setNotes(response.data.data);
} catch (error) {}
};
const handleAddNote = async (tasktext) => {
const addNoteInformation = {
email: localStorage.getItem("tokenEmail"),
taskText: tasktext,
date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
};
if (addNoteInformation.email && addNoteInformation.taskText) {
try {
await axios.post(
"http://localhost:9000/api/note/add",
addNoteInformation
);
} catch (error) {}
}
};
const handleDeleteNote = async (id) => {
const deletedInformaion = {
email: localStorage.getItem("tokenEmail"),
noteId: id,
};
if (deletedInformaion.email && deletedInformaion.noteId) {
await axios.post(
"http://localhost:9000/api/note/deleted",
deletedInformaion
);
}
};
useEffect(() => {
getNotes();
}, []);
return (
<>
<Navbar />
<div className="container">
<div className="row">
{notes
.filter((notes) => notes != null)
.map((notes, index) => (
<Note
key={index}
text={notes.text}
date={notes.date}
id={notes._id}
deletenote={handleDeleteNote}
getnote={getNotes}
/>
))}
<AddNote getnote={getNotes} addnote={handleAddNote} />
</div>
</div>
</>
);
};
note.jsx
const Note = (props) => {
const handleDeleteNote = () => {
props.deletenote(props.id);
props.getnote();
};
return (
<>
<div className="col-lg-4 col-md-6 col-sm-12 p-4">
<div className="note d-flex flex-column">
<span className="note-top overflow-auto m-2 ps-2">{props.text}</span>
<div className="note-bottom d-flex justify-content-between flex-row-reverse mt-auto">
<small>{props.date}</small>
<MdDelete
onClick={handleDeleteNote}
className="delete-icon"
size="1.3rem"
color="#bb86fc"
/>
</div>
</div>
</div>
</>
);
};
addNote.jsx
const AddNote = (props) => {
let addNoteText = useRef();
const handleAddNote = async () => {
props.addnote(addNoteText.current.value);
props.getnote();
addNoteText.current.value = "";
};
return (
<div className="col-lg-4 col-md-6 col-sm-12 p-4">
<div className="add-note-box d-flex flex-column justify-content-between">
<div className="top-box">
<textarea
placeholder="یادداشت خود را وارد کنید ......"
class="form-control"
rows={7}
ref={addNoteText}
></textarea>
</div>
<BsFillPlusCircleFill
onClick={handleAddNote}
className="plus-icon"
size="1.3rem"
color="#bb86fc"
/>
</div>
</div>
);
};
You didn't update state after sending the respective add and delete request, that's why you need to refresh to get the updated data. This is the fix:
const handleAddNote = async (tasktext) => {
const addNoteInformation = {
email: localStorage.getItem("tokenEmail"),
taskText: tasktext,
date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
};
if (addNoteInformation.email && addNoteInformation.taskText) {
try {
await axios.post(
"http://localhost:9000/api/note/add",
addNoteInformation
);
setNotes([...notes, addNoteInformation]); // update state using spread operator and put the new one to the end
} catch (error) {}
}
};
const handleDeleteNote = async (id) => {
const deletedInformaion = {
email: localStorage.getItem("tokenEmail"),
noteId: id,
};
if (deletedInformaion.email && deletedInformaion.noteId) {
await axios.post(
"http://localhost:9000/api/note/deleted",
deletedInformaion
);
setNotes(notes.filter(note => note.id !== id)) // update state using filter function
}
};
Alternativelly, when adding notes, you can update state using the response object from your request, since the id of newly created note maybe generated by your database. It dependes on the actual response object from the axios request:
const response = await axios.post();
setNotes([...notes, response.data]);
as u see in the code I'm tryin to get the "ProductionName" from the server "getManuficturedProduction" and display that into the input and after that I want to get the input value and post it to the server but idk why my set state doesn't update and still show me the default value.when i log my set state "assignProductToProductionline" i can see that my "ProductionName" did not updated
const [assignProductToProductionline, SetAssignProductToProductionline] =
useState({
Id: "",
ProductionCode: "",
ProductionName: "",
});
useEffect(() => {
loadProductionLine();
}, []);
const [productionLineName, SetProductionLineName] = useState([]);
const loadProductionLine = async () => {
const result = await axios.get(
"url"
);
SetProductionLineName(result.data);
};
const getManuficturedProduction = async () => {
var res = await axios.get(
`url`
);
var GetInfo = res.data.Result;
SetAssignProductToProductionline({
ProductionName: `${GetInfo.Name}`,
});
};
const { Id, ProductionCode, ProductionName } = assignProductToProductionline;
const onInputChange = (e) => {
SetAssignProductToProductionline({
...assignProductToProductionline,
[e.target.name]: e.target.value,
});
};
const onSubmit = async (e) => {
await axios
.post(
"url",
assignProductToProductionline
)
.catch(function (error) {
if (error.response) {
return toast.error(error.response.data);
}
});
navigate("/productionLineProduct");
};
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5 mt-5">
<form onSubmit={(e) => onSubmit(e)}>
<div className="form-group">
<select
className="form-control form-control-md mb-2 "
type="text"
name="Id"
value={Id}
onChange={(e) => onInputChange(e)}
autoComplete="off"
>
{productionLineName.map((cs) => (
<option key={cs.Id} value={cs.Id}>
{cs.ProductionLineName}
</option>
))}
</select>
</div>
<div className="form-group mb-2">
<input
id="customeProductionCode"
type="number"
className="form-control form-control-md"
name="ProductionCode"
value={ProductionCode}
onChange={(e) => onInputChange(e)}
autoComplete="off"
onInput={(e) => (e.target.value = e.target.value.slice(0, 9))}
/>
<a
className="btn btn-outline-success px-4"
onClick={(e) => getManuficturedProduction(e)}
>
check it
</a>
<div className="mt-2">
<input
className="text-success w-50"
name="ProductionName"
defaultValue=""
value={ProductionName}
placeholder={ProductionName}
onChange={(e) => onInputChange(e)}
/>
</div>
</div>
<button className="btn btn-primary w-25 ">save</button>
</form>
</div>
</div>
);
};
export default AssignProductToProductionLine;
{
you have to use assignProductToProductionline.ProductionName.
This line
const { Id, ProductionCode, ProductionName } = assignProductToProductionline;
creates a constant that is initialized with the first value and never changed.
Ill be changing the key shortly. Using the code below I should be able to load a list of movies from the API and each movie should be linked to it's Provider Link website. using
the upMovieDetail. can anyone help point me in the right direction? I have a feeling it has something to do with the component being re-renderd after the click?
here is the codesandbox if you'd rather try to fix it here.. --
https://codesandbox.io/s/movieapp-searchbar-forked-qv1o6
const key ="fde5ddeba3b7dec3fc1f51852ca0fb95";
const getUpMovieDetail = (movieId) => {
//const [movieId, setMovieId] = useState([]);
const url = `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=${key}`;
return fetch(url);
};
function UpMovieDetail({ movieItem }) {
const [searchLink, setSearchLink] = useState(null);
useEffect(() => {
getUpMovieDetail(movieItem.id)
.then((res) => res.json())
.then((res) => {
setSearchLink(res?.results?.US?.link);
});
}, [movieItem.id]);
return (
<ul className="flexed-search">
{searchLink.map((item) =>
<div className="poster-container" key={item.id}>
<li className="list-item">
<a target="_blank" rel="noopener noreferrer" href={searchLink}
onclick={((event) => {event.preventDefault()})}>
<img className="image-element" tabIndex="0" alt="movie poster"
title={`--Title: ${item.title}-- --Description:
${item.overview}-- --Vote Average: ${item.vote_average}`}
aria-label={item.title}
src={`https://image.tmdb.org/t/p/w500${item.poster_path}`} />
</a>
<h3 className="posterTitle">{item.title}</h3>
</li>
</div>
)}
</ul>
);
};
const SearchBar = () => {
const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
// Input Field
const onUserInput = ({target}) => {
setInput(target.value);
};
// Api Call
const SearchApi = (event) => {
const aUrl = "https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
const newUrl = aUrl +'&query=' + input;
event.preventDefault();
fetch(newUrl)
.then((response) => response.json())
.then((data) => {
setSearch(data.results);
})
.catch((error) => {
console.log('Error!! Data interupted!:', error)
})
};
return (
// Heading
<div>
<div className="container">
<h1>Movie Search Extravaganza!</h1>
{/* Input Field and Button Form */}
<form onSubmit={SearchApi}>
<input value={input} onChange={onUserInput} type="text" className="searchbar" aria-label="searchbar" placeholder="search" required/>
<br></br>
<button type="submit" aria-label="searchbutton" className="searchBtn">Movie Express Search</button>
</form>
<h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
</div>
<div className="byName-container">
{search.map((item) => (
<UpMovieDetail key={item.id} movieItem={item} />
))}
</div>
</div>
)};
export default SearchBar;```
[1]: http://codesandbox.io/s/movieapp-searchbar-forked-qv1o6
[2]: https://codesandbox.io/s/movieapp-searchbar-forked-qv1o6
From the first render it throws the error because searchLink is null.
Try this:
{
searchLink && searchLink.length && searchLink.map((item) =>
...
}