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)}
Related
Hello i was worked on crud app everything is worked fine but when i create delete route i cannot post data to server i get empty string and error cannot get if i follow get link i try to comment all delete methods but still no one is working even toast are stopped working works only navigate buttons ..
Server
index.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "crud_contact",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", function(req,res){
console.log('Hello');
db.query('SELECT * FROM contact_db', function (error, result) {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const {name, email, contact} = req.body;
const sqlInsert =
`INSERT INTO contact_db (name,email, contact)
VALUES (?, ?, ?)`;
db.query(sqlInsert, [name, email, contact], (error,result) => {
res.send(result);
if(error) {
console.log(error);
}
});
})
// app.delete("/api/remove/:id", (req, res) => {
// const {id} = req.params;
// const sqlRemove =
// `DElETE FROM contact_db WHERE id = ?`;
// db.query(sqlRemove, id , (error,result) => {
// if(error) {
// console.log(error);
// }
// });
// })
//
app.get("/", (req, res) => {
// app.listen(5000, () => {
// con.connect(function(err) {
// if (err) throw err;
// console.log("Connected!");
// var sql = `INSERT INTO contact_db(name,email, contact)
// VALUES('popas','berazumis#gmail.com',8585858)`;
// con.query(sql, function (err, result) {
// if (err) throw err;
// console.log("record inserted");
// });
// });
// });
});
app.listen(5000, () => {
console.log("Listening port 5000");
});
Client
Add edit user
AddEdit.js
import React, { useState, useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
const initiaState = {
name: "",
email: "",
contact: "",
};
const AddEdit = () => {
const [state, setState] = useState(initiaState);
const { name, email, contact } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
if (!name || !email || !contact) {
toast.error("Please fill all labels below");
} else {
axios
.post("http://localhost:5000/api/post", {
name,
email,
contact
})
.then(() => {
setState({ name: "", email: "", contact: "" });
})
.catch((err) => toast.error(err.response.data));
setTimeout(() => navigate.push("/"), 500);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setState({ ...state, [name]: value });
};
return (
<div style={{ marginTop: "100px" }}>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "cener",
}}
onSubmit={handleSubmit}
>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
placeholder="Type Name..."
value={name}
onChange={handleInputChange}
/>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Type Email..."
value={email}
onChange={handleInputChange}
/>
<label htmlFor="contact">Contact</label>
<input
type="number"
id="contact"
name="contact"
placeholder="Type contact number"
value={contact}
onChange={handleInputChange}
/>
<Link to="/">
<input type="submit" value="save" />
<input type="button" value="Go Back" />
</Link>
</form>
</div>
);
};
export default AddEdit;
Home.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Home.css";
import { toast } from "react-toastify";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
const loadData = async () => {
const response = await axios.get("http://localhost:5000/api/get");
setData(response.data);
};
useEffect(() => {
loadData();
}, []);
/* const deleteContact = (id) => {
if(window.confirm("Are you sure that you wanna delete contact")) {
axios.delete(`http://localhost:5000/api/remove/${id}`);
toast.success("Contact Deleted Successfully");
setTimeout(() => loadData(), 500);
}
}
*/
return (
<div style={{ marginTop: "150px" }}>
<Link to="addContact">
<button className="btn btn-contact">Add contact</button>
</Link>
<table className="styled-table">
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
<th style={{ textAlign: "center" }}>Contact</th>
<th style={{ textAlign: "center" }}>Action</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.contact}</td>
<td>
<Link to={`/update/${item.id}`}>
<button className="btn btn-edit" >Edit</button>
</Link>
<button className="btn btn-delete" /*onClick={() => deleteContact}*/ >Delete</button>
<Link to={`/view/${item.id}`}>
<button className="btn btn-view">View</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Home;
When you create a app.delete route, you no longer use POST method on your client side, you need to use the DELETE method.
Client Side Example
const res = await axios.delete('https://example.com/delete', { data: { answer: 42 } });
Server Side Example
app.delete('/delete', async(req, res,next) => {
console.log('req.body', req.body)
//prints { data: { answer: 42 } }
})
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 have a table in a modal whose code looks like this.
<div>
<Table>
<tbody>
{props.data.map((p) => <>
<tr>
<th> STC </th>
<th> Edit Text</th>
</tr>
<tr index={p}>
<td key={p.stc}><h3>{p.stc}</h3></td>
<td >
<TextField name={p.stc} type="text" value={p.readValue} onChange={handleChange} required={true} size="small" label="Required" variant="outlined" />
</td>
</tr>
</>)}
</tbody>
</Table>
<div >
<Button disabled={inputState.disable} className="buttonStyle" onClick={(e) => submit()}>SUBMIT</Button>
<Button onClick={handleClose}>CANCEL</Button>
</div>
</div>
And their corresponding functions and declarations as below -
const [formInput, setFormInput] = useReducer(
(state, newState) => ({ ...state, ...newState }),
);
const [inputState, setInputState] = useState({disable: true});
const handleOpen = (e) => {
setOpen(true);
};
const handleClose = () => {
window.location.reload(false);
setOpen(false);
};
const [readValue, writeValue] = useState("");
const submit = (e) => {
console.log("Submitted!")
handleClose();
}
const handleChange = (event) => {
const newValue = event.target.value;
writeValue(event.target.value)
setInputState({disable: event.target.value===''})
}
I want to -
disable the buttons until and unless all the TextFields are filled.
In handleClose(), is there any alternate solution for clearing the values of TextFields in stead of window.reload?
The format looks like the picture I'm attaching below-
enter image description here
import React, { useState } from "react";
import "./style.css";
export default function App() {
const textFields = ["field1", "field2"];
const [inputValue, setInputValue] = useState({});
const [buttonDisabled, setButtonDisabled] = useState(true);
const validateButton = accInputs => {
let disabled = false;
textFields.forEach(field => {
if (!accInputs[field]) {
disabled = true;
}
});
return disabled;
};
const handleChange = ({ currentTarget }) => {
const { name, value } = currentTarget;
const inputObj = {};
inputObj[name] = value;
const accInputs = { ...inputValue, ...inputObj };
setInputValue(accInputs);
setButtonDisabled(validateButton(accInputs));
};
const handleSubmit = () => {
console.log("submit clicked");
};
const handleCancel = () => {
const inputObj = {};
textFields.forEach(field => {
inputObj[field] = "";
});
setInputValue(inputObj);
};
return (
<div>
<table border="1px">
<tr>
<th> STC </th>
<th> Edit Text</th>
</tr>
{textFields.map(field => {
console.log("rendered");
return (
<tr>
<td>
<h3>p.stc</h3>
</td>
<td>
<input
placeholder="required *"
value={inputValue[field]}
name={field}
onChange={handleChange}
/>
</td>
</tr>
);
})}
</table>
<input type="submit" disabled={buttonDisabled} onClick={handleSubmit} />
<input type="submit" onClick={handleCancel} value="cancel" />
</div>
);
}
can be easily achieved with the above code. Please refer working example here
updated to add second point aswell.
I need help because i'm stuck in my reactjs project. I'm trying to make multiple search input box with different filter each in reactJS, but i can't achieve it with more than one filter. I tried googling it but i cannot make it work.
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.state.filterTitle} onChange={this.filterList}/>
<input name="filterYear" type="text" value={this.state.filterYear} onChange={this.filterList}/>
<input name="filterReso" type="text" value={this.state.filterReso} onChange={this.filterList}/>
</form>
}
filterList = (event) => {
var items = this.state;
var updatedItems = this.state.items.filter(item => {
var filterTitle = this.state.filterTitle != "" ? item.titulo.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
var filterYear = this.state.filterYear != "" ? item.ano.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
var filterReso = this.state.filterReso != "" ? item.reso.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
return filterTitle && filterYear && filterReso;
})
this.setState({ updatedItems: updatedItems });
console.log(updatedItems);
}
UPDATE 1:
new code so far, please help!
handleSearchFilter = (event) => {
const inputValue = event.target.value;
this.setState({ input: inputValue });
this.filterList(inputValue);
};
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.filterTitle} onChange={(e)=>this.handleSearchFilter(e)} />
<input name="filterYear" type="text" value={this.filterYear} onChange={(e)=>this.handleSearchFilter(e)} />
<input name="filterReso" type="text" value={this.filterReso} onChange={(e)=>this.handleSearchFilter(e)} />
</form>
}
filterList = (inputValue) => {
const {items, updatedItems} = this.state;
const itemsUpdate = this.state.items.filter(item => {
var filterTitle = item.titulo.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
var filterYear = item.ano.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
var filterReso = item.reso.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
return filterTitle + filterYear + filterReso;
})
this.setState({ updatedItems: itemsUpdate });
console.log(updatedItems);
}
first you need to save search key seperate in state then make AND or OR comparison to retrive result like this
import React from "react";
class TestPage extends React.Component {
state = {
items: [
{
titulo: "titulo1",
ano: "ano1",
reso: "reso1",
},
{
titulo: "titulo2",
ano: "ano2",
reso: "reso2",
},
],
updatedItems: [],
filterTitle: "",
filterYear: "",
filterReso: "",
};
searchFilter = () => {
return (
<form>
<input
name="filterTitle"
type="text"
value={this.filterTitle}
onChange={(e) => this.handleSearchFilter(e, "filterTitle")}
/>
<input
name="filterYear"
type="text"
value={this.filterYear}
onChange={(e) => this.handleSearchFilter(e, "filterYear")}
/>
<input
name="filterReso"
type="text"
value={this.filterReso}
onChange={(e) => this.handleSearchFilter(e, "filterReso")}
/>
</form>
);
};
handleSearchFilter = (event, key) => {
const inputValue = event.target.value;
this.setState({ [key]: inputValue }, () => {
this.filterList();
});
};
filterList = () => {
const itemsUpdate = this.state.items.filter((item) => {
var filterTitle =
item.titulo
.toLowerCase()
.indexOf(this.state.filterTitle.toLowerCase()) > -1;
var filterYear =
item.ano.toLowerCase().indexOf(this.state.filterYear.toLowerCase()) >
-1;
var filterReso =
item.reso.toLowerCase().indexOf(this.state.filterReso.toLowerCase()) >
-1;
return filterTitle && filterYear && filterReso;
});
this.setState({ updatedItems: itemsUpdate }, () => {
console.log(this.state.updatedItems);
});
};
renderList = () => {
const { updatedItems } = this.state;
return (
<div>
{updatedItems.map((updatedItem) => {
return (
<div>
{updatedItem.titulo}
{updatedItem.ano}
{updatedItem.reso}
</div>
);
})}
</div>
);
};
render() {
return (
<div>
{this.searchFilter()}
{this.renderList()}
</div>
);
}
}
export default TestPage;
First of all you need to store the input values corresponding to each input in state and post that you need to filter the items array.
I assume you wish to do an AND operation on filters. IF you wish to do an OR operation just change it in the code below
handleSearchFilter = (event) => {
const {value, name} = event.target;
this.setState({ [name]: value }, () => {
this.filterList();
}); // use setState callback to now filter the list
};
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.state.filterTitle} onChange={this.handleSearchFilter} />
<input name="filterYear" type="text" value={this.state.filterYear} onChange={(e)=>this.handleSearchFilter} />
<input name="filterReso" type="text" value={this.state.filterReso} onChange={this.handleSearchFilter} />
</form>
}
filterList = () => {
const {items, updatedItems, filterTitle, filterYear, filterReso} = this.state;
const itemsUpdate = this.state.items.filter(item => {
var filterTitleRes = item.titulo.toLowerCase().indexOf(filterTitle.toLowerCase()) > 1;
var filterYearRes = item.ano.toLowerCase().indexOf(filterYear.toLowerCase()) > 1;
var filterResoRes = item.reso.toLowerCase().indexOf(filterReso.toLowerCase()) > 1;
return filterTitleRes && filterYearRes && filterResoRes;
// Change the above condition to or if you wish to do an OR check
})
this.setState({ updatedItems: itemsUpdate });
console.log(itemsUpdate);
}
You can use js-search for optimized searching across multiple keys in JSON object.
In your case, you can simply create a smaller JSON array where you only store keys in which you want to search for example
import * as JsSearch from 'js-search';
var theGreatGatsby = {
isbn: '9781597226769',
title: 'The Great Gatsby',
author: {
name: 'F. Scott Fitzgerald'
},
tags: ['book', 'inspirational']
};
var theDaVinciCode = {
isbn: '0307474275',
title: 'The DaVinci Code',
author: {
name: 'Dan Brown'
},
tags: ['book', 'mystery']
};
var angelsAndDemons = {
isbn: '074349346X',
title: 'Angels & Demons',
author: {
name: 'Dan Brown',
},
tags: ['book', 'mystery']
};
var search = new JsSearch.Search('isbn');
search.addIndex('title');
search.addIndex(['author', 'name']);
search.addIndex('tags')
search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]);
search.search('The'); // [theGreatGatsby, theDaVinciCode]
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