Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Komanda: npm add @babel/plugin-proposal-class-properties --save
- import React, {Component} from 'react';
- class App extends Component {
- constructor(props){
- super(props)
- this.onHandleUsers = this.onHandleUsers.bind(this)
- this.tekstas = "a";
- this.state = {
- isLoaded: false,
- users: []
- }
- }
- handleUserChange = (e) => {
- const {value} = e.target
- this.onHandleCurrentUsers(value)
- this.tekstas = this.onHandleCurrentUsers(userId)
- }
- onHandleUsers() {
- fetch("http://localhost:3000/api/users")
- .then(res => res.json())
- .then(result => {
- this.setState({
- isLoaded: true,
- users: result
- })
- })
- .catch(e => console.log(e))
- }
- onHandleCurrentUsers(userId) {
- const data = {userId: userId}
- fetch("http://localhost:3000/api/user", {
- method: 'POST',
- headers: { "Content-Type": "application/json"},
- body: JSON.stringify(data)
- })
- .then(res => res.json())
- .then(result => {
- this.setState({
- isLoaded: false,
- currentUser: result
- })
- })
- .catch(e => console.log(e))
- }
- render() {
- const {currentUser} = this.state
- return (
- <div>
- <div>
- {
- currentUser && <div>{currentUser.name} {currentUser.surname}</div>
- }
- </div>
- <div>
- <form onSubmit={this.handleUserChange}>
- <label>
- <input
- name="userId"
- type="number"
- //value={this.handleUserChange}
- onChange={this.handleUserChange}
- />
- </label>
- <input type="submit" value="Submit" />
- </form>
- {this.tekstas}
- </div>
- <div> </div>
- </div>
- )
- }
- }
- export default App
- UserApi:
- class UserApiController {
- constructor(){
- this.getUsers = this.getUsers.bind(this)
- this.findUser = this.findUser.bind(this)
- }
- _usersList(){
- return [
- {id: 1, name: 'Jonas', surname: 'Grybas'},
- {id: 2, name: 'Ernestas', surname: 'Arlauskas'},
- {id: 3, name: 'Fetras', surname: 'Fetrovicius'},
- {id: 4, name: 'Gvazdykas', surname: 'Ornamentas'},
- {id: 5, name: 'Jurgis', surname: 'Jonaitis'}
- ]
- }
- getUsers(req, res, next){
- const users = this._usersList()
- return res.json(users)
- }
- findUser(req, res, next) {
- const userId = parseInt(req.body.userId) || 0
- const users = this._usersList()
- const amount = users.length
- let result = {}
- for (let i = 0; i < amount; i++) {
- let user = users[i]
- if(user.id == userId){
- result = user
- break
- }
- }
- return res.json(result)
- }
- }
- module.exports = UserApiController
- babelrc:
- {
- "presets": ["@babel/preset-env", "@babel/preset-react"],
- "plugins": [
- "@babel/plugin-proposal-class-properties"]
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement