-
-
Save joskid/d9fbf8ed3b7d32cada852731e7bcb8e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Item from './Item'; | |
| import './App.css'; | |
| class App extends Component { | |
| constructor(){ | |
| super(); | |
| this.state = { | |
| items: [11,21,31] | |
| } | |
| } | |
| numSort = (a, b) => { | |
| if(a < b){ | |
| return -1; | |
| }else if(b < a){ | |
| return 1; | |
| }else{ | |
| return 0; | |
| } | |
| } | |
| addNum = (ev) => { | |
| ev.preventDefault(); | |
| //get the sorted values from state.items | |
| // find the highest number in items, | |
| // increment it, | |
| // update state | |
| let _items = this.state.items.sort(this.numSort); | |
| let max = Math.max( ..._items ) + 1; | |
| _items.push(max); | |
| this.setState({items: _items}); | |
| } | |
| addFromLS = (num) => { | |
| // accept a number | |
| // get the values from state.items | |
| // add the new value to the array | |
| // remove duplicates | |
| // sort the array | |
| // update state | |
| let _items = this.state.items; | |
| _items.push(num); | |
| _items = Array.from(new Set(_items)).sort(this.numSort); | |
| this.setState({items: _items}); | |
| } | |
| componentDidMount(){ | |
| // check localStorage for an array | |
| // if it exists parse the array | |
| // call addFromLS method for each number | |
| let _items = localStorage.getItem('myNums'); | |
| if(_items){ | |
| _items = JSON.parse(_items); | |
| _items.forEach( this.addFromLS ); | |
| } | |
| } | |
| render() { | |
| return ( | |
| <div className="App"> | |
| <p><button onClick={this.addNum}>Add an Item</button></p> | |
| {this.state.items && this.state.items.map( (item) => ( | |
| <Item key={item} num={item} /> | |
| )) | |
| } | |
| </div> | |
| ); | |
| } | |
| } | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment