Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. document.addEventListener('DOMContentLoaded', function(){
  5. class CarsDbList extends React.Component {
  6. handleBtnClick = (id) => {
  7. if (typeof this.props.onDel === 'function') {
  8. this.props.onDel(id);
  9. }
  10. };
  11.  
  12. render () {
  13. const liCss = {
  14. borderBottom : '1px solid black',
  15. width : 300,
  16. marginBottom : 5,
  17. display : 'flex',
  18. justifyContent : 'space-between',
  19. listStyle : 'dot',
  20. }
  21. const css = {
  22. display : 'inline-block',
  23. marginRight : 15,
  24. padding : 5,
  25. };
  26. const li = this.props.cars.map(e => {
  27. return <li key={e.id} style={liCss}>
  28. <span style={css}>{e.brand} {e.name}</span>
  29. <button style={css}
  30. onClick={ev => this.handleBtnClick(e.id)}>
  31. Sprzedany</button>
  32. </li>
  33. });
  34. return <ul>
  35. {li}
  36. </ul>;
  37. }
  38. }
  39.  
  40. class CarsDbManager extends React.Component {
  41. constructor(props) {
  42. super(props);
  43. this.state = {
  44. data : null,
  45. };
  46. }
  47.  
  48. handleCarSold = (id) => {
  49. const data = this.state.data.slice();
  50. const newData = data.filter((e) => e.id !== id);
  51. fetch(`http://localhost:3000/cars/${id}`, {
  52. method : 'DELETE',
  53. })
  54. .then( () => {
  55. this.setState({
  56. data : newData,
  57. });
  58. });
  59. };
  60.  
  61. componentDidMount() {
  62. fetch('http://localhost:3000/cars')
  63. .then(resp => {
  64. if (!resp.ok) throw new Error('^^');
  65. return resp.json();
  66. })
  67. .then(respJson => this.setState({
  68. data : respJson,
  69. }));
  70. }
  71.  
  72. render () {
  73. if (!this.state.data) return null;
  74. return <div>
  75. <CarsDbList cars={this.state.data} onDel={this.handleCarSold} />
  76. </div>;
  77. }
  78. }
  79.  
  80. class App extends React.Component {
  81. render () {
  82. return <CarsDbManager />;
  83. }
  84. }
  85.  
  86. ReactDOM.render(
  87. <App />,
  88. document.getElementById('app')
  89. );
  90. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement