am trying to delete a row based on product code entered, i have 2 functions, one is for search and another is for delete..
Search Function
const handleName = e => {
const idAddProducts = e.target.value;
e.preventDefault();
pnName({ ...poName, idaddproducts: idAddProducts });
handleTable(idAddProducts);
// handleSubmit(idAddProducts);
console.log(poName);
};
async function handleTable(idAddProducts) {
const id = poName.idaddproducts;
const res = await fetch(
"http://localhost:4000/productslist/" + idAddProducts
);
const data = await res.json();
pnName(data.data);
console.log(data.data);
}
useEffect(() => {
handleTable();
}, []);
Another one is Delete Function
const handleN = e => {
const idAddProducts = e.target.value;
e.preventDefault();
pnName({ ...poName, idaddproducts: idAddProducts });
handleSubmit(idAddProducts);
console.log(poName);
};
async function handleSubmit(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/delete/" + idAddProducts
);
const data = await res.json();
pnName(data.data);
console.log(data.data);
}
useEffect(() => {
handleSubmit();
}, []);
Here is the Rendering Part where i map the searched result
<TableBody>
{poName && poName.length ? (
poName.map(row => (
<TableRow key={row.idaddproducts}>
<TableCell component="th" scope="row">
{row.idaddproducts}
</TableCell>
<TableCell component="th" scope="row">
{row.productName}
</TableCell>
<TableCell align="right">{row.productId}</TableCell>
<TableCell align="right">{row.productBrand}</TableCell>
<TableCell align="right">{row.productQuantity}</TableCell>
<TableCell align="right">{row.productPrice}</TableCell>
<TableCell align="right">{row.productType}</TableCell>
</TableRow>
))
) : (
<span>Not Found</span>
)}
</TableBody>
</Table>
</TableContainer>
<div style={{ paddingBlockEnd: "0px" }}>
<Fab color="secondary" aria-label="edit" onClick={handleN}>
<EditIcon />
</Fab>
</div>
So when i add the handleSubmit function directly in to handleName, its getting deleted as i type, so i had to create seperate function as HandleN and call handle submit so that when i click button it should execute,
instead sql throws as Error:
ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value:
'undefined'
or
Error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value:
'[object]%20[object]'
Any help ?
export default function DeleteProductsForm() {
const initialState = {
idaddproducts: "",
productName: "",
productId: "",
productBrand: "",
productQuantity: "",
productPrice: "",
productType: ""
};
const [values, setValues] = React.useState(initialState);
const handleName = e => {
const idAddProducts = e.target.value;
console.log(idAddProducts);
e.preventDefault();
setValues({ ...values, [e.target.name]: idAddProducts });
handleList1(idAddProducts);
console.log(values);
};
const handleN = e => {
const idAddProducts = values.idaddproducts;
console.log(idAddProducts);
e.preventDefault();
setValues({ ...values, [e.target.name]: idAddProducts });
handleList(idAddProducts);
console.log(values);
};
async function handleList1(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/" + idAddProducts
);
const data = await res.json();
setValues(data.data);
console.log(data.data);
}
useEffect(() => {
handleList1();
}, []);
async function handleList(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/delete/" + idAddProducts
);
const data = await res.json();
setValues(data.data);
console.log(data.data);
}
useEffect(() => {
handleList();
}, []);
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off" align="center">
<div className={classes.formGroup}>
<FormControl>
<Input
type="search"
label="Product ID"
variant="outlined"
size="small"
placeholder="Enter Product Code"
value={values.idaddproducts}
name="idaddproducts"
onChange={e => handleName(e)}
/>
</FormControl>
<Button onClick={e => handleN(e)}>Click</Button>
{values && values.length ? (
values.map(row => <h5 key={row.idaddproducts}>{row.productName}</h5>)
) : (
<h5>Not Found</h5>
)}
</div>
</form>
);
}
if i delete handleList1 function it works fine.. but it wont display data
Related
I want to make selector for the user to select name of section, and according to what he select, view the section types in another selector, then when he select the section type display the students in a table.
I write code and get the data true but because i use (async..await) so the project get very slow and then closed.
What's the wrong?
function Teacher() {
const [data1, setData1] = useState([]);
const [data2, setData2] = useState([]);
const [data3, setData3] = useState([]);
const [SectionName, setSectionName] = useState('بستان');
const [Type, setType] = useState('أ');
useEffect(() => {
async function getName() {
await Axios
.get(`http://localhost:3003/getSectionsName`)
.then(result => setData1(result.data));
}
getName()
}, []);
const nameSelector = (
<select className="custom-select" onChange={(e) => {
const selectedSectionName = e.target.value;
setSectionName(selectedSectionName);
}}>
{data1.map((item) =>
<option key={item.id} value={item.SectionName}>
{item.SectionName}
</option>
)}
</select>
)
async function typeSelector() {
await Axios.put(`http://localhost:3003/getSectionTypes`, { SectionName: SectionName }).then(result => setData2(result.data))
}
const typeSelect = (
typeSelector(),
<select className="custom-select" onChange={(e) => {
const selectedSectionType = e.target.value;
setType(selectedSectionType);
}}>
{data2.map((item) =>
<option key={item.id}>
{item.Type}
</option>
)}
</select>
)
function student() {
Axios.put(`http://localhost:3003/getStudents`, { Type: Type, SectionName: SectionName }).then(result => setData3(result.data))
}
const studentTable = (
student(),
<table className="table" >
<thead className="thead-dark">
<tr>
<th scope="col">الطلاب</th>
</tr>
</thead>
<tbody>
{data3.map(item => {
return <tr key={item.Id}>
<td>{item.FullName}</td>
</tr>
})}
</tbody>
</table>
)
return (
<div className="container p-2">
<h4> اختر الصف </h4>
{nameSelector}
<br />
<h4> اختر الشعبة </h4>
{typeSelect}
<br /><br />
<h4>
{studentTable}
</h4>
</div>
)
}
export default Teacher;
async function typeSelector() {
await Axios.put(`http://localhost:3003/getSectionTypes`, { SectionName: SectionName }).then(result => setData2(result.data))
}
const typeSelect = (
typeSelector(),
...
is plain wrong - it means you're calling typeSelector() with the comma sequencing operator as a side effect of rendering the component, and likely end up in an infinite render loop. This would happen with a non-async typeSelector() function too.
You will need to wrap those fetch calls within suitable useEffect() hooks, maybe like so (I took the liberty of also extracting the components into, well, components.)
function StudentTable({ students }) {
return (
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">الطلاب</th>
</tr>
</thead>
<tbody>
{students.map((item) => {
return (
<tr key={item.Id}>
<td>{item.FullName}</td>
</tr>
);
})}
</tbody>
</table>
);
}
function NameSelector({ sections }) {
return (
<select
className="custom-select"
onChange={(e) => setSectionName(e.target.value)}
>
{sections.map((item) => (
<option key={item.id} value={item.SectionName}>
{item.SectionName}
</option>
))}
</select>
);
}
function TypeSelect({ types }) {
return (
<select
className="custom-select"
onChange={(e) => setType(e.target.value)}
>
{types.map((item) => (
<option key={item.id} value={item.id}>
{item.Type}
</option>
))}
</select>
);
}
function Teacher() {
const [sections, setSections] = useState([]);
const [types, setTypes] = useState([]);
const [students, setStudents] = useState([]);
const [sectionName, setSectionName] = useState("بستان");
const [type, setType] = useState("أ");
// Load sections on mount
useEffect(() => {
Axios.get(
`http://localhost:3003/getSectionsName`,
).then((result) => setSections(result.data));
}, []);
// Load types based on selected section
useEffect(() => {
Axios.put(`http://localhost:3003/getSectionTypes`, {
SectionName: sectionName,
}).then((result) => setTypes(result.data));
}, [sectionName]);
// Load students based on section and type
useEffect(() => {
Axios.put(`http://localhost:3003/getStudents`, {
Type: type,
SectionName: sectionName,
}).then((result) => setStudents(result.data));
}, [sectionName, type]);
return (
<div className="container p-2">
<h4> اختر الصف </h4>
<NameSelector sections={sections} />
<br />
<h4> اختر الشعبة </h4>
<TypeSelect types={types} />
<br />
<br />
<h4>
<StudentTable students={students} />
</h4>
</div>
);
}
export default Teacher;
Try useEffect() that has a dependency sectionName. When it changes, then you will call typeSelector() and student().
const [data1, setData1] = useState([]);
const [data2, setData2] = useState([]);
const [data3, setData3] = useState([]);
const [sectionName, setSectionName] = useState('بستان');
const getName = async () => {
const data = await Axios.get(`http://localhost:3003/getSectionsName`);
setData1(data);
};
const typeSelector = async () => {
const data = await Axios.put(`http://localhost:3003/getSectionTypes`, {
SectionName: SectionName
});
setData2(data);
};
const student = async () => {
const data = Axios.put(`http://localhost:3003/getStudents`, {
Type: Type,
SectionName: SectionName
});
setData3(data);
};
useEffect(() => {
getName();
}, []);
useEffect(() => {
typeSelector();
student();
}, [sectionName]);
I want to dynamically render the data when filtering from start to end. The logic only displays one date value at a time. I want to display the E_NodeB Cell_Name Date E_RAB_Setup_Success_Rate Data_Traffic_DL Data_Traffic_UL UL_Throughput when I filter the from and to dates
`const data = "http://localhost:8080/sites";
const SelectSingle = () => {
var traffic = [];
var rab = [];
var newData = [];
const [sites, setsites] = useState([]);
const [selectedSite, setSelectedSite] = useState([]);
const [startDate, setDate] = useState();
const [endDate, setEndDate] = useState();
// 1
const handleChange = (event) => {
event.preventDefault();
const siteSelected = event.target.value;
const itemSelected = sites.filter(
(site) => site.Cell_Name === siteSelected
);
setSelectedSite(itemSelected);
};
// Start Date
// Traffice_Date
const handleDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
newData.push(dateChosen);
setSelectedSite(dateChosen);
};
// End date
const handleEndDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
setSelectedSite(dateChosen);
};
// Get Date Function
const getDate = (e) => {
const start = e.target.value;
const [year, month, day] = start.split("-");
const newDate = `${day}/${month}/${year}`;
return newDate;
};
useEffect(() => {
fetch(data)
.then((res) => res.json())
.then((data) => setsites(data));
});
selectedSite.map((site) => {
rab.push(site.E_RAB_Setup_Success_Rate);
traffic.push(site.Traffice_Date);
});
const state = {
labels: traffic,
datasets: [
{
label: "E_RAB_Setup_Success_Rate",
backgroundColor: "rgba(75,192,192,1)",
borderColor: "rgba(0,0,0,1)",
borderWidth: 2,
data: rab,
},
],
};
return (
<div>
<div className="data-class">
<select
onChange={(e) => {
handleChange(e);
}}
>
{sites.map((site, index) => (
<option value={site.Cell_Name} key={index}>
{site.Cell_Name}
</option>
))}
</select>
<h2>From</h2>
<input
type="date"
value={startDate}
onChange={(e) => {
handleDate(e);
}}
name="startDate"
/>
<h2>To</h2>
<input
type="date"
value={endDate}
onChange={(e) => {
handleEndDate(e);
}}
name="endDate"
/>
</div>
<div>
<table>
<thead>
<tr>
<th>E_NodeB</th>
<th>Date</th>
<th>Cell_Name</th>
<th>E_RAB_Setup_Success_Rate</th>
<th>Data_Traffic_DL</th>
<th>Data_Traffic_UL</th>
<th>UL_Throughput</th>
</tr>
</thead>
{selectedSite.map((site, index) => (
<tbody key={index}>
<td>{site.eNodeB_Name}</td>
<td>{site.Cell_Name}</td>
<td>{site.Traffice_Date}</td>
<td>{site.E_RAB_Setup_Success_Rate}</td>
<td>{site.Data_Traffic_DL}</td>
<td>{site.Data_Traffic_UL}</td>
<td>{site.G_UL_Throughput_IK}</td>
</tbody>
))}
</table>
<Line
data={state}
options={{
title: {
display: true,
text: "Plot of E_RAB_Setup_Success_Rate",
fontSize: 20,
},
legend: {
display: true,
position: "right",
},
}}
/>
</div>
</div>
);
};
export default SelectSingle;
`
Backend code
const express = require("express");
const cors = require("cors");
const mysql = require("mysql2");
const app = express();
const connection = mysql.createConnection({
host: "localhost",
user: "a",
password: "123",
database: "aa",
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL Server!");
});
app.use(cors());
app.get("/", function (req, res) {
connection.query("SELECT * FROM africell_data LIMIT 10", (err, rows) => {
if (err) throw err;
res.json(rows);
});
});
app.get("/sites", function (req, res) {
connection.query(
`SELECT eNodeB_Name,Cell_Name,Traffice_Date,E_RAB_Setup_Success_Rate,Data_Traffic_DL,Data_Traffic_UL,G_UL_Throughput_IK FROM africell_data`,
(err, rows) => {
if (err) throw err;
res.json(rows);
}`enter code here`
);
});
app.listen(8080, (req, res) => {
console.log(`The app is connected on port 8080`);
});
enter image description here
It appears in your handleDate and handleEndDate functions, you're filtering only for sites which have the specified date (site.Traffice_Date === getDate(e)), which would explain why you're only seeing one date. Try updating the code in your filter block to look for all sites with date above or below your start and end dates, as desired.
I have an input field in which I am pre populating the value of, with the value from the DB. it is a record that already exists, in which I would like to edit. The input field however, is not letting me edit the field. Please find it below:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useHistory } from "react-router-dom";
const EditServicesPage = () => {
const history = useHistory()
const [myData, setMyData] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [showEditButton, setShowEditButton] = useState(false);
const [fields, setFields] = useState({
updatedByCNUM: "",
content: "",
site: ""
})
var idFromListServicesPage = history.location.state.id
console.log("22: " + idFromListServicesPage)
useEffect(() => {
axios
.post('/getDocToEdit', {id : idFromListServicesPage})
.then((res) => {
console.log("line 28 esp.js: " + res.data)
setMyData(res.data);
setIsLoading(true);
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
.finally(() => {
setIsLoading(false);
});
}, []);
const deleteById = (id) => {
console.log(id);
axios
.post(`/deleteDoc`, { id: id })
.then(() => {
console.log(id, " worked");
window.location = "/admin/content";
})
.catch((error) => {
// Handle the errors here
console.log(error);
});
};
const handleInputChange = e => setFields(f => ({...f, [e.target.name]: e.target.value}))
const editById = (id, site, content, updatedByCNUM) => {
console.log(id, site, content, updatedByCNUM);
axios
.post(
'/editDoc',
({
id: id,
location: site,
content: content,
updatedByCNUM: updatedByCNUM
})
)
.then(() => {
console.log(id, " worked");
window.location = "/admin/content";
})
.catch((error) => {
console.log(error);
});
};
const onClickEdit = (e, _id) => {
e.preventDefault();
var site = document.getElementById("site").value;
var content = document.getElementById("content").value;
var updatedByCNUM = document.getElementById("updatedByCNUM").value;
console.log(site, content, updatedByCNUM)
editById(_id, site, content, updatedByCNUM);
};
const onTyping = (value) => {
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
return (
<table id="customers">
<h1>Edit Services Page</h1>
<tr>
<th>site</th>
<th>content</th>
<th>updatedByCNUM</th>
<th>Actions</th>
</tr>
<tr>
<td>
<input
// ref={site.ref}
type="text"
value={myData.site}
onInput={(e) => onTyping(e.target.value)}
onChange={handleInputChange}
placeholder={myData.site}
name="site"
id="site"
/>{" "}
{/* <input
type="text"
placeholder={site}
onChange={(e) => onTyping(e.target.value)}
name="site"
id="site"
/> */}
</td>
<td>
<input
// ref={content.ref}
type="text"
value={myData.content}
onInput={(e) => onTyping(e.target.value)}
onChange={handleInputChange}
placeholder={myData.content}
name="content"
id="content"
/>
</td>
<td>
<input
type="text"
placeholder={myData.updatedByCNUM}
name="updatedByupdatedByCNUMhide"
id="updatedByupdatedByCNUMhide"
readOnly
/>{" "}
</td>
<td>
{/* <input type="hidden" placeholder={myData.updatedByCNUM} name="updatedByCNUM" id="updatedByCNUM" value={updatedByCNUM}/>{" "} */}
</td>
<td>
<button
onClick={(e) => {
e.preventDefault();
deleteById(idFromListServicesPage);
}}
disabled={isLoading}
>
Delete
</button>
<button
onClick={(e) => {
e.preventDefault();
editById(idFromListServicesPage);
}}
>
Edit
</button>
{showEditButton && (
<button onClick={(e) => onClickEdit(e, idFromListServicesPage)}>Submit Edit</button>
)}
</td>
</tr>
</table>
);
};
export default EditServicesPage;
showButton:
const onTyping = (value) => {
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
when I try to type into the input field, it doesn't allow me to type, but keeps the pre existing value there already. how can I fix this?
You need a state which has the initial values from the DB
const [data, setData] = useState({
site: newData.site || "",
content: newData.content || "",
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setData((currentData) => ({ ...currentData, [name]: value }));
};
return (
// .....
<input
// ref={site.ref}
type="text"
value={data.site} // use data.site here instead of the newData
onChange={handleInputChange}
placeholder={myData.site}
name="site"
id="site"
/>
// .....
);
Just add setMyData like this:
const onTyping = (name, value) => {
setMyData({ ...myData, [name]: value });
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
And
onInput={(e) => onTyping(e.target.name, e.target.value)}
I'm using functional component and I'm getting JSOS object from local file And in component I'm setting that JSON in some state.
After that few object I spliced(deleted) from that setState. But again in onchange function I want all the JSON object but here I'm getting updated json means few are deleted, Is there any method I can store all JSON object in some place? can anybody help me in this.
const StudyDetails = () => {
const [supplyPlan, setSupplyPlan] = useState([]);
const getSupplyPlanDetails = useCallback(
async () => {
try {
const payload = {
studyName: studyDetails?.studyName
? studyDetails?.studyName
: query.get("name"),
country: [],
depot: [],
material: [],
site: [],
inTransientMaterial,
};
const res = await getSupplyPlan(payload);
//setSupplyPlan(res);
console.log(res)
// setSupplyPlan(supplyData)
} catch (err) {
setSupplyPlan([]);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
useEffect(() => {
getSupplyPlanDetails();
}, [ getSupplyPlanDetails]);
const onChange = (e) => {debugger
console.log(supplyData)
}
return (
<div>
<Checkbox
onChange={onChange}
>
In Transit
</Checkbox>
{supplyPlan?.map((item, index) => (
<Fragment key={index}>
<SupplyChain item={item} />
<Divider className="supply-chain-divider" />
</Fragment>
))}
</div>
)
}
I'm splicing few object in supplyChain component:
const SupplyChain = ({ item }) => {
useEffect(() => {
let data = [];
if (item && item.inTransit.length != 1) {
item &&
item.inTransit &&
item.inTransit.length > 0 &&
item.inTransit.map((intrans, index) => {
if (
intrans.from === item.depots?.packagingDepot?.[0]?.depotName &&
intrans.to === "sites"
) {
let directPath = item.inTransit.splice(index, 1);
setDirectSite(directPath);
}
setFilterJson(item.inTransit);
// eslint-disable-next-line react-hooks/exhaustive-deps
item = { ...item, filterJson: item.inTransit };
});
}
}
So if again when I click on onchange function I want all objects of JSON.
please someone help me in this
I'm working on a recipe site using API from a third party and want to change the number of servings (which is output from the API data) when clicking the + & - button. I tried assigning the output serving amount <Servings>{recipe.servings}</Servings> in a variable and useState to update it but it kept showing errors. I would appreciate any help (preferably using react Hooks). Thanks :)
Here is my code:
const id = 716429;
const apiURL = `https://api.spoonacular.com/recipes/${id}/information`;
const apiKey = "34ac49879bd04719b7a984caaa4006b4";
const imgURL = `https://spoonacular.com/cdn/ingredients_100x100/`;
const {
data: recipe,
error,
isLoading,
} = useFetch(apiURL + "?apiKey=" + apiKey);
const [isChecked, setIsChecked] = useState(true);
const handleChange = () => {
setIsChecked(!isChecked);
};
return (
<Section>
<h2>Ingredients</h2>
<ServingsandUnits>
{recipe && (
<ServingsIncrementer>
<p>Servings: </p>
<Minus />
<Servings>{recipe.servings}</Servings>
<Plus />
</ServingsIncrementer>
)}
<ButtonGroup>
<input
type="checkbox"
id="metric"
name="unit"
checked={isChecked}
onChange={handleChange}
/>
<label htmlFor="male">Metric</label>
</ButtonGroup>
</ServingsandUnits>
</Section>
};
My custom hook is called useFetch:
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
fetch(url, { signal: abortCont.signal })
.then((res) => {
if (!res.ok) {
// error coming back from server
throw Error("Could not fetch the data for that resource");
}
return res.json();
})
.then((data) => {
setIsLoading(false);
setData(data);
setError(null);
})
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
} else {
// auto catches network / connection error
setIsLoading(false);
setError(err.message);
}
});
return () => {
abortCont.abort();
};
}, [url]);
return { data, isLoading, error };
};
export default useFetch;