- CustomerAdd.js
handleFormSubmit = (e) => { e.preventDefault(); this.addCustomer() .then((resposne)=> { console.log(resposne.data); this.props.stateRefresh(); }) this.setState({ file: null, userName: '', birthday: '', sex: '', job: '', fileName: '' }) //window.location.reload(); // reload the page and get clients data }
- server.js
- Processing request of adding client data and uploading profile image file
- multer library for processing file uploading
npm i --save multer
- mapping imgae folder path on upload folder from server
- add client data on MySQL DB
- create upload folder
const multer = require('multer'); const upload = multer({dest: './upload'}); // uploaded user profile image here app.use('/image', express.static('./upload')); // shared uploaded folder with users so users can access the profile images though image folder path app.post('/api/customers', upload.single('image'), (req,res)=>{ let sql = 'INSERT INTO CUSTOMER VALUES (null, ?, ?, ?, ?, ?)'; //id value is auto-increment let image = '/image/' + req.file.filename; //multer library allocate unique random file name let name = req.body.name; let birthday = req.body.birthday; let sex = req.body.sex; let job = req.body.job; let params = [image, name, birthday, sex, job]; //binding each variables to each sql ? connection.query(sql, params, (err,rows, fields) => { res.send(rows); //print message to client }) })
- App.js
- Reload clinet information through changing state of the parent comonent
class App extends Component { constructor(props){ super(props); this.state={ customers: "", completed: 0 } } stateRefresh = () => { this.state={ customers: "", completed: 0 } this.callApi() .then(res => this.setState({customers: res})) .catch(err => console.log(err)); } componentDidMount(){ this.timer = setInterval(this.progress, 20); this.callApi() .then(res => this.setState({customers: res})) .catch(err => console.log(err)); } callApi = async () => { const response = await fetch('/api/customers'); const body = await response.json(); return body; } progress = () => { const { completed } = this.state; this.setState({ completed: completed >= 100 ? 0 : completed +1}); } render() { const { classes } = this.props; return ( <div> <Paper className={classes.root}> <Table className={classes.table}> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>Image</TableCell> <TableCell>Name</TableCell> <TableCell>Birthday</TableCell> <TableCell>Sex</TableCell> <TableCell>Job</TableCell> </TableRow> </TableHead> <TableBody> { this.state.customers ? this.state.customers.map(c => { return( <Customer key={c.id} id={c.id} image={c.image} name={c.name} birthday={c.birthday} sex={c.sex} job={c.job}/> )}) : <TableRow> <TableCell colSpan = '6' align='center'> <CircularProgress className = {classes.progress} varient="determinate" value = {this.state.completed}></CircularProgress> </TableCell> </TableRow> } </TableBody> </Table> </Paper> <CustomerAdd stateRefresh={this.stateRefresh}></CustomerAdd> </div> ); } }