Last active
April 15, 2019 13:08
-
-
Save benkissi/ad088a429f174bdec72852d20d66207a to your computer and use it in GitHub Desktop.
Context blog
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"; | |
const AppContext = React.createContext(); | |
class AppProvider extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
todos: [] | |
}; | |
this.addTodo = this.addTodo.bind(this); | |
this.completed = this.completed.bind(this); | |
} | |
addTodo(todo) { | |
const { todos } = this.state; | |
const newTodo = { | |
id: Math.floor(Math.random() * (1000 - 1)) + 1, | |
todo: todo, | |
createdAt: Date.now(), | |
completed: false | |
}; | |
this.setState({ | |
todos: todos.concat(newTodo) | |
}); | |
} | |
completed(id) { | |
const { todos } = this.state; | |
todos.forEach(todo => { | |
if (todo.id === id) { | |
todo.completed = !todo.completed; | |
} | |
}); | |
this.setState({ | |
todos: todos | |
}); | |
} | |
render() { | |
return ( | |
<AppContext.Provider | |
value={{ | |
todos: this.state.todos, | |
addTodo: this.addTodo, | |
completed: this.completed | |
}} | |
> | |
{this.props.children} | |
</AppContext.Provider> | |
); | |
} | |
} | |
const AppConsumer = AppContext.Consumer; | |
export { AppProvider, AppConsumer }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment