Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created October 23, 2018 21:05
Show Gist options
  • Save prof3ssorSt3v3/b5d9b98843de686c65d41c3249b478ac to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/b5d9b98843de686c65d41c3249b478ac to your computer and use it in GitHub Desktop.
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