How to pending button show approved on click event by reactjs - reactjs

When I click the "pending" button, the status does not change with this code, and shows the message
TypeError: this.state.data.map is not a function
Please help me!
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: "farid",
age: 15,
status: "pending"
},
{
id: 2,
name: "kamal",
age: 15,
status: "pending"
}
],
}
}
movementappTDClick = (id) => () => {
const index = this.state.data.findIndex((data) => {
return data.id === id
})
let data = Object.assign({}, this.state.data[index]);
console.log('data is', data);
data.status = "approved"
console.log("sec data is", data);
this.setState({ data });
};
render() {
return (
<div className="App">
<Card>
<CardBody>
<Table>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
{this.state.data && this.state.data.map(movement => (
<tr key={movement.id}>
<th>{movement.id}</th>
<td>{movement.name}</td>
<td>{movement.age} </td>
<td>
<button
onClick={this.movementappTDClick(movement.id)}
>
{movement.status}
</button>
</td>
</tr>
))}
</tbody>
</Table>
</CardBody>
</Card>
</div>
);
}
}

try to modify your movementappTDClick function.
movementappTDClick = index => {
const data = [...this.state.data];
const row = data[index];
row.status = "approved";
data.splice(index, 1, row);
this.setState({ data });
};
render() {
return (
<div className="App">
<Card>
<CardBody>
<Table>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
{this.state.data &&
this.state.data.map((movement, index) => (
<tr key={movement.id}>
<th>{movement.id}</th>
<td>{movement.name}</td>
<td>{movement.age} </td>
<td>
<button onClick={() => this.movementappTDClick(index)}>
{movement.status}
</button>
</td>
</tr>
))}
</tbody>
</Table>
</CardBody>
</Card>
</div>
);
}
}

I modified your code. Please check this.
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{
id: 1,
name: "farid",
age: 15,
status: "pending"
},
{
id: 2,
name: "kamal",
age: 15,
status: "pending"
}
],
}
}
movementappTDClick = (index) => () => {
const { data } = this.state;
data[index] = {
...data[index],
status: 'approved'
}
this.setState({ data }); };
render() {
const { data } = this.state;
return (
<div className="App">
<Card>
<CardBody>
<Table>
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
{data && _.map((data || []), (movement, index) => (
<tr key={movement.id}>
<th>{movement.id}</th>
<td>{movement.name}</td>
<td>{movement.age} </td>
<td>
<button
onClick={this.movementappTDClick(index)}
>
{movement.status}
</button>
</td>
</tr>
))}
</tbody>
</Table>
</CardBody>
</Card>
</div>
);
}
}

Related

Deleting necessary data (with checkbox) in React

Need to delete the data that is highlighted by the checkbox. When I click on the checkbox, in all checkboxes the done becomes: true, then false and i can't remove the highlights. When the remove function is worked, only the first element is deleted. How can write a remove function.
import React from "react";
import { useState } from "react";
const App = () => {
const [user, setUser] = useState([
{id:1, name:"Peter", surname:"Robinson"},
{id:2, name:"Ann", surname:"Walker"},
{id:3, name:"James", surname:"Allen"},
])
const [check, setCheck] = useState({done: false})
const remove = () => {
if (check.done) {
}
}
return <>
<table className="table table-bordered">
<thead>
<tr>
{Object.keys(user[0]).map((elm,i) => {
return <td key={i}>
{elm.charAt(0).toUpperCase() + elm.slice(1)}
</td>
})}
</tr>
</thead>
<tbody>
{
user.map((elem, ind) => {
return <tr key={ind}>
<td>{elem.id}</td>
<td>{elem.name}</td>
<td>{elem.surname}</td>
<td>
<input type="checkbox" name="" id="" onChange={() => setCheck({done: check.done ? false : true})}/>
</td>
</tr>
})
}
</tbody>
</table>
<button className="btn btn-primary ms-2" onClick={() => remove()}>Delete selected</button>
</>
}
export default App;
Thank you.
You should handle the checked state for each user independently, then delete the ones with the checked flag at true:
import React from 'react';
import { useState } from 'react';
const App = () => {
const [user, setUser] = useState([
{ id: 1, name: "Peter", surname: "Robinson", checked: false },
{ id: 2, name: "Ann", surname: "Walker", checked: false },
{ id: 3, name: "James", surname: "Allen", checked: false }
]);
const toggleCheck = (id) => {
const checkedIdx = user.findIndex((u) => u.id === id);
if (checkedIdx === -1) return;
const updatedUser = [...user];
updatedUser[checkedIdx].checked = !updatedUser[checkedIdx].checked;
setUser(updatedUser);
};
const remove = () => {
setUser([...user].filter((u) => !u.checked));
};
return (
<>
<table className="table table-bordered">
<thead>
<tr>
{Object.keys(user[0]).map((elm, i) => {
return (
<td key={i}>{elm.charAt(0).toUpperCase() + elm.slice(1)}</td>
);
})}
</tr>
</thead>
<tbody>
{user.map((elem, ind) => {
return (
<tr key={elem.id}>
<td>{elem.id}</td>
<td>{elem.name}</td>
<td>{elem.surname}</td>
<td>
<input
type="checkbox"
name=""
id=""
onChange={() => toggleCheck(elem.id)}
value={elem.checked}
/>
</td>
</tr>
);
})}
</tbody>
</table>
<button className="btn btn-primary ms-2" onClick={() => remove()}>
Delete selected
</button>
</>
);
};
export default App;
Here is the code to a working sandbox.

Display a table in React using different components

I'm just starting to learn React and what I'm trying to do is to display a table. I'm doing it using 3 components: App.js, DisplayTable.js, and TableRows.js. The reason I'm doing it this way is that later on, I will need certain rows of the table to be displayed subject to different conditions. I don't get any error messages, but the table is not being displayed. This is my code:
App.js:
import Form from './components/Form'
import { useState } from 'react'
import TableDisplay from './components/TableDisplay'
const App = () => {
const [rows, setRows] = useState([
{
id:1,
description:'',
semester:'',
prefix:'ENG',
number:'368/371',
grade:'',
editing:''
},
{
id:2,
description:'',
semester:'',
prefix:'',
number:'',
grade:'',
editing:''
},
{
id:3,
description:'',
semester:'',
prefix:'',
number:'',
grade:'',
editing:''
},
])
return (
<div className="container">
<Form/>
<TableDisplay rows={rows}/>
</div>
);
}
export default App;
TableDisplay.js:
import TableRows from "./TableRows"
const TableDisplay = ({rows}) => {
return (
<>
{rows.map((row) => {
<TableRows key={row.id} row={row}/>
})}
</>
)
}
export default TableDisplay
TableRows.js:
import React from 'react'
const TableRows = ({row}) => {
return (
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Description</th>
<th scope="col">Semester</th>
<th scope="col">Prefix</th>
<th scope="col">Number</th>
<th scope="col">Grade</th>
<th scope="col">Editing</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">{row.id}</th>
<td>{row.description}</td>
<td>{row.semester}</td>
<td>ENG</td>
<td>368/371</td>
<td>{row.grade}</td>
<td><button type="button" className="btn btn-warning">Edit</button></td>
</tr>
<tr>
<th scope="row">{row.id}</th>
<td>{row.description}</td>
<td>{row.semester}</td>
<td>ENG</td>
<td>368/371</td>
<td>{row.grade}</td>
<td><button type="button" className="btn btn-warning">Edit</button></td>
</tr>
<tr>
<th scope="row">{row.id}</th>
<td>{row.description}</td>
<td>{row.semester}</td>
<td>ENG</td>
<td>368/371</td>
<td>{row.grade}</td>
<td><button type="button" className="btn btn-warning">Edit</button></td>
</tr>
</tbody>
</table>
</div>
)
}
export default TableRows
You should remove bracket
const TableDisplay = ({ rows }) => {
return (
<>
{rows.map((row) => <TableRows key={row.id} row={row} />)}
</>
);
};
or add return
const TableDisplay = ({ rows }) => {
return (
<>
{rows.map((row) => {
return <TableRows key={row.id} row={row} />;
})}
</>
);
};

No class .db.model.FileDB entity with id 0 exists?

I have a REST API in Spring Boot with JPA and Spring Security ,I manage to upload a file and download it successfully but when I try to delete an existing user object in my database by ID, I get the following error message:
org.springframework.dao.EmptyResultDataAccessException: No class model.FileDB entity with id
undefined exists!
I am new to react / springboot and I cannot find the exact error please HELP.
fileDB MODEL
#Entity
#Table(name = "files")
public class FileDB {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
FileController.java
#DeleteMapping("/files/{id}")
public ResponseEntity<String> deleteFile(#PathVariable String id){
storageService.deleteFile(id);
return new ResponseEntity<>("file deleted", HttpStatus.OK);
}
FileService.java
public void deleteFile(String id) {
fileDBRepository.deleteById(id);
}
******react
export default class UploadFiles extends Component {
constructor(props) {
super(props);
this.selectFiles = this.selectFiles.bind(this);
this.upload = this.upload.bind(this);
this.uploadFiles = this.uploadFiles.bind(this);
this.state = {
selectedFiles: undefined,
progressInfos: [],
message: null,
fileInfos: [],
files:[]
};
}
componentDidMount() {
UploadService.getFiles().then((response) => {
this.setState({
fileInfos: response.data,
});
});
}
deleteFile=(fileId) =>{
axios.delete("http://localhost:8181/files/"+fileId)
.then(response => {
if(response.data !=null){
this.setState({
files:this.state.files.filter(file => file.id !== fileId)
});
}
});
};
render()
{
//code
<Table bordered hover striped variant="dark" >
<thead>
<tr>
<th> List of Files </th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
fileInfos &&
fileInfos.map((file, id) =>
<tr key = {id}>
<td> <a href={file.url}>{file.name}</a> </td>
<td>
<ButtonGroup>
<Button onClick={this.deleteFile.bind(this,id)}
size="sm" variant="outline-danger">
<FontAwesomeIcon icon={faTrash} />
</Button>
{' '}
<Button size="sm" variant="outline-danger">
<FontAwesomeIcon icon={faEye} />
</Button>
</ButtonGroup>
</td>
</tr>
)
}
</tbody>
</Table>
}
Your Java code APi it's working properly, i thin the problem is in your client side, if the response of UploadService.getFiles() is something like this:
{
....
data:[
{
"id": "afd564",
"name": "hello",
"link": "this the link"
}
]
....
}
export default class UploadFiles extends Component {
constructor(props) {
super(props);
this.selectFiles = this.selectFiles.bind(this);
this.upload = this.upload.bind(this);
this.uploadFiles = this.uploadFiles.bind(this);
this.state = {
selectedFiles: undefined,
progressInfos: [],
message: null,
fileInfos: [],
files:[]
};
}
componentDidMount() {
UploadService.getFiles().then((response) => {
this.setState({
fileInfos: response.data,
});
});
}
deleteFile=(fileId) =>{
axios.delete("http://localhost:8181/files/"+fileId)
.then(response => {
if(response.data !=null){
this.setState({
files:this.state.files.filter(file => file.id !== fileId)
});
}
});
};
render()
{
//code
<Table bordered hover striped variant="dark" >
<thead>
<tr>
<th> List of Files </th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
fileInfos &&
fileInfos.map((file, id) =>
<tr key = {id}>
<td> <a href={file.url}>{file.name}</a> </td>
<td>
<ButtonGroup>
<Button onClick={this.deleteFile.bind(this,file.id)}
size="sm" variant="outline-danger">
<FontAwesomeIcon icon={faTrash} />
</Button>
{' '}
<Button size="sm" variant="outline-danger">
<FontAwesomeIcon icon={faEye} />
</Button>
</ButtonGroup>
</td>
</tr>
)
}
</tbody>
</Table>
}

React collapse row onClick

I have data that I need to show in table, for all rows I would like to use collapse function. Now I have working code that is collapsing all rows on click, but in what way I can collapse only one already clicked?
This is my code:
class Data extends React.Component {
constructor(props) {
super(props);
this.state = {
datas: [
{name: "or1", status: 11},
{name: "or3", status: 2},
{name: "or2", status: 22},
],
expanded: [],
isOpen: true,
};
}
toogleContent(openIs) {
this.setState({
isOpen: !openIs
})
}
render() {
return (
<Table responsive>
<thead className="text-primary">
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{this.state.datas.map((data, i) => (
<tr id={i} onClick={this.toogleContent.bind(this, this.state.isOpen)}>
<td>{data.name}</td>
<td><Collapse isOpen={this.state.isOpen}>
{data.status}</Collapse>
</td>
</tr>
))}
</tbody>
</Table>
)
}
}
I used their indexes to find out if they are opened or not, but you can use their names too, or add at data object a key isOpened =>
state={
isOpenIndexes = []
}
toogleContent(index) {
// we check if already opened
this.state.isOpenIndexes.find(openedIndex => openedIndex ===index ) ?
this.setState({
isOpenIndexes: this.state.isOpenIndexes.filter(openedIndex => openedIndex!==index)
})
:
this.setState({
isOpenIndexes: isOpenIndexes.concat([index])
})
}
{datas.map((data, i) => (
<tr id={i} onClick={this.toogleContent.bind(this, i)} isOpened={this.state.isOpenIndexes.find(openedIndex => openedIndex ===i )}>
<td>{data.name}</td>
<td>{data.status}</td>
</tr>
))}

How to handle a onClick method in a component?

I believe I have my props setup correctly, but I keep getting "Cannot read property 'props' of undefined"
Child component:
const SearchResults = props => (
<div>
<div className="row" ><h4 style={{margin:"auto", marginBottom:"15px"}}>Search Results:</h4></div>
<table className="table table-striped">
<thead>
<tr>
{props.labels.map(label => ( <th key={label.Id}>{label.DisplayName}</th>))}
</tr>
</thead>
<tbody>
{ props.contracts.map((contract, i) => <tr key={i} data-id={contract.Id} onClick={() => this.props.handleContract(contract.Fields.filter(field => field.DataField==="IDXT001").map(field => field.DataValue))} className="clickable-row">{contract.Fields.map( docs => <td key={docs.Id}><span id={docs.DataField}>{docs.DataValue}</span></td>)}</tr> )}
</tbody>
</table>
</div>
)
Parent:
class SearchPage extends React.Component {
constructor(props) {
super(props);
this.state = {
labels: [],
contracts: [],
formValues:"",
pdfs:[],
id:"",
};
}
<SearchResults
labels={this.state.labels}
contracts={this.state.contracts}
pdfs={this.state.pdfs}
handleContract={this.onClick}
/>
You need to change this.props.handleContract to props.handleContract. this doesn't exist in your functional component.
const SearchResults = props => (
<div>
<div className="row" ><h4 style={{ margin: "auto", marginBottom: "15px" }}>Search Results:</h4></div>
<table className="table table-striped">
<thead>
<tr>
{props.labels.map(label => (<th key={label.Id}>{label.DisplayName}</th>))}
</tr>
</thead>
<tbody>
{props.contracts.map((contract, i) => <tr key={i} data-id={contract.Id} onClick={() => props.handleContract(contract.Fields.filter(field => field.DataField === "IDXT001").map(field => field.DataValue))} className="clickable-row">{contract.Fields.map(docs => <td key={docs.Id}><span id={docs.DataField}>{docs.DataValue}</span></td>)}</tr>)}
</tbody>
</table>
</div>
);
On your parent, make sure you have bound the onClick function as mentioned in the comments.
class SearchPage extends React.Component {
constructor(props) {
super(props);
this.state = {
labels: [],
contracts: [],
formValues: "",
pdfs: [],
id: ""
};
}
onClick = () => {
// Bind the function like this.
}
render() {
return (
<SearchResults
labels={this.state.labels}
contracts={this.state.contracts}
pdfs={this.state.pdfs}
handleContract={this.onClick}
/>
);
}
}

Resources