I fetch from db new data and render (setState) after importing excel data, problem not working. I have played around to trying to get it working so copied the fetch from getItems to simplifiedFunction. I had also problem when starting the rendering was in infinite loop, but then I added a parameter (value) to control when to fetch. In the code there is also a excel export, that works fine .I’m a beginner with React js
App.js
simplifiedFunction (value) {
let b = value
//this.state.upd=b
if (b==true)
{
fetch('http://localhost:3000/crud')
.then(response => response.json())
.then(items => this.setState({items}))
.catch(err => console.log(err))
}
in render….
<Excelfileinp
simplifiedFunction = {this.simplifiedFunction}
/>
Excelfileinp.js
this call back to App.js
this.props.simplifiedFunction(true)
code part
fetch('http://localhost:3000/crudexcel', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(mdata1)
})
.then(response => response.json())
.then(item => {
if(Array.isArray(item)) {
this.props.simplifiedFunction(true)
} else {
console.log('failure')
}
})
.catch(err => console.log(err))
};
App.js
import React, { Component } from 'react'
import { Container, Row, Col } from 'reactstrap'
import ModalForm from './Components/Modals/Modal'
import DataTable from './Components/Tables/DataTable'
import ReactExport from "react-export-excel";
import FileInput from './FileInput';
import Excelfileinp from './Excelfileinp';
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;
class App extends Component {
state = {
items: []
}
getItems(value){
if (value === true)
{
fetch('http://localhost:3000/crud')
.then(response => response.json())
.then(items => this.setState({items}))
.catch(err => console.log(err))
}
}
addItemToState = (item) => {
this.setState(prevState => ({
items: [...prevState.items, item]
}))
}
updateState = (item) => {
const itemIndex = this.state.items.findIndex(data => data.id === item.id)
const newArray = [
// destructure all items from beginning to the indexed item
...this.state.items.slice(0, itemIndex),
// add the updated item to the array
item,
// add the rest of the items to the array from the index after the replaced item
...this.state.items.slice(itemIndex + 1)
]
this.setState({ items: newArray })
}
deleteItemFromState = (id) => {
const updatedItems = this.state.items.filter(item => item.id !== id)
this.setState({ items: updatedItems })
}
componentDidMount(){
//this.state.upd=true
this.getItems(true)
//this.state.upd=false
}
simplifiedFunction (value) {
let b = value
//this.state.upd=b
if (b==true)
{
//this.getItems(true)
fetch('http://localhost:3000/crud')
.then(response => response.json())
.then(items => this.setState({items}))
.catch(err => console.log(err))
}
//this.state.upd=false
}
render() {
return (
<Container className="App">
<Row>
<Col>
<h1 style={{margin: "20px 0"}}>CRUD Database</h1>
</Col>
</Row>
<Row>
<Col>
<DataTable items={this.state.items} updateState={this.updateState} deleteItemFromState={this.deleteItemFromState} />
</Col>
</Row>
<Row>
<Col>
<ModalForm buttonLabel="Add Item" addItemToState={this.addItemToState}/>
<div>
<Excelfileinp
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
</Col>
</Row>
<ExcelFile element={<button>Download Data</button>}>
<ExcelSheet data={this.state.items} name="items">
<ExcelColumn label="id" value="id"/>
<ExcelColumn label="first" value="first"/>
<ExcelColumn label="last" value="last"/>
<ExcelColumn label="email" value="email"/>
<ExcelColumn label="phone" value="phone"/>
<ExcelColumn label="location" value="location"/>
<ExcelColumn label="hobby" value="hobby"/>
</ExcelSheet>
</ExcelFile>
</Container>
)
}
}
export default App
Excelfileinp.js
import React, { Component } from 'react'
import * as XLSX from 'xlsx';
function renderData(passData) {
let json = [];
for(let i = 1; i < passData.length; i++) {
//if (i==1)
//{
let body = {};
body['id'] = passData[i][0];
body['first'] = passData[i][1];
body['last'] = passData[i][2];
body['email'] = passData[i][3];
body['phone'] = passData[i][4];
body['location'] = passData[i][5];
body['hobby'] = passData[i][6];
json.push(body);
//}
}
return json;
}
class Excelfileinp extends React.Component {
constructor( props ) {
super( props );
this.inputFileRef = React.createRef();
this.onFileChange = this.handleFileChange.bind( this );
this.onBtnClick = this.handleBtnClick.bind( this );
}
handleFileChange( e ) {
/*Selected files data can be collected here.*/
//console.log( e.target.files );
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
const mdata0 = renderData(jsonData);
const mdata = JSON.stringify(mdata0);
const mdata1 = JSON.parse(mdata);
fetch('http://localhost:3000/crudexcel', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(mdata1)
})
.then(response => response.json())
.then(item => {
if(Array.isArray(item)) {
//this.props.setupd=true
this.props.simplifiedFunction(true)
//this.props.setupd=false
//variable.props.toggle()
} else {
console.log('failure')
}
})
.catch(err => console.log(err))
};
reader.readAsArrayBuffer(file);
}
handleBtnClick() {
/*Collecting node-element and performing click*/
this.inputFileRef.current.click();
}
render() {
return (
<input
type="file"
ref={this.inputFileRef}
onChange={this.onFileChange}
/>
)
}
} export default Excelfileinp;
debug done.. coming to App.js but fetch do nothing. get no error
Dev Johnny is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.