Created
November 5, 2019 12:56
-
-
Save Ileriayo/92afda20813348e46233a800d1ad9d0f to your computer and use it in GitHub Desktop.
App.js using classfull, stateful, container components - Original file: https://github.com/victor-nach/react-record-management/blob/fetch-add-new-record-%237/src/App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import axios from 'axios'; | |
import Table from './components/tables'; | |
import AddForm from './components/addForm'; | |
import EditForm from './components/editForm'; | |
import './App.css'; | |
class App extends Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
users: [], | |
status: false, | |
currentUser: { | |
id: null, | |
firstName: '', | |
surname: '', | |
dob: '', | |
age: '', | |
height: '', | |
} | |
} | |
} | |
fetchUsers = async () => { | |
const {data} = await axios.get('https://cashbox-backend-node.herokuapp.com/records'); | |
this.setState({ users: [ ...data.data ] }); | |
} | |
componentDidMount = () => { | |
this.fetchUsers(); | |
} | |
editUser = user => { | |
this.setState({ status: true, currentUser: { ...user } }); | |
} | |
updateUser = (id, updatedUser) => { | |
this.setState({ | |
status: false, | |
currentUser: this.state.users.map(user => (user.id === id ? updatedUser : user)) | |
}); | |
} | |
addUser = async (user) => { | |
user.id = user.length + 1; | |
const res = await axios.post('https://cashbox-backend-node.herokuapp.com/records', user); | |
this.setState({ users: [...this.state.users, user] }); | |
} | |
deleteUser = id => { | |
this.setState({ | |
status: false, | |
currentUser: this.state.users.filter(user => user.id !== id) | |
}); | |
} | |
render = () => { | |
return ( | |
<div className='container'> | |
<h1> Record Management</h1> | |
<div> | |
{ | |
this.state.status ? ( | |
<div> | |
<h2>Edit User</h2> | |
<EditForm | |
currentUser={this.state.currentUser} | |
updateUser={this.updateUser} | |
setEditStatus={this.state.status} | |
editStatus={this.state.status} | |
/> | |
</div> | |
) : ( | |
<div className=''> | |
<h2> Add user</h2> | |
<AddForm addUser={this.addUser} /> | |
</div> | |
) | |
} | |
</div> | |
<div className=''> | |
<h2>View Users</h2> | |
<Table users={this.state.users} deleteUser={this.deleteUser} editUser={this.editUser} /> | |
</div> | |
</div> | |
) | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment