import React from 'react'
export const { Provider, Consumer } = React.createContext()
export default class ProviderComponent extends React.Component {
state = {
todos: [],
showInput: false
}
updateContextState = data => this.setState(data)
fetchAndSetState = () => {
this.timer = setTimeout(() => this.setState({
todos: [
{
todo: 'Go to potions class'
},
{
todo: 'Buy new robes'
},
{
todo: 'Visit Hagrid'
}
]
}), 1000)
}
componentDidMount() {
this.fetchAndSetState()
}
componentWillUnmount() {
clearTimeout(this.timer)
}
render() {
const store = {
...this.state,
updateContextState: this.updateContextState
}
return (
<Provider value={store}>
{this.props.children}
</Provider>
)
}
}
import React from 'react';
import Header from './components/Header'
import CustomInput from './components/Input'
import CustomList from './components/List'
import ProviderComponent from './Context'
import styles from './index.module.css'
const App = () => (
<ProviderComponent>
<div className={styles.container}>
<div className={styles.todoList} >
<Header />
<CustomInput
type='text'
placeholder='Add New Todo'
/>
<CustomList />
</div>
</div>
</ProviderComponent>
)
export default App;
import React from 'react'
import { Consumer } from '../../Context'
import styles from './index.module.css'
class CustomListItem extends React.Component {
// ... (component logic)
render() {
return (
<li>
<Consumer>
{({ updateContextState, todos }) => (
<span
onClick={() => {
const newTodos = todos.filter(element => element.todo !== text)
updateContextState({ todos: newTodos })
}}
>
<i className="fas fa-trash" />
</span>
)}
</Consumer>
// ... (component logic)
</li>
)
}
}
export default CustomListItem
import React from 'react'
import { Consumer } from '../../Context'
import styles from './index.module.css'
class CustomListItem extends React.Component {
// ... (component logic)
render() {
return (
<li>
<Consumer>
{({ updateContextState, todos }) => (
<span
onClick={() => {
const newTodos = todos.filter(element => element.todo !== text)
updateContextState({ todos: newTodos })
}}
>
<i className="fas fa-trash" />
</span>
)}
</Consumer>
// ... (component logic)
</li>
)
}
}
export default CustomListItem
import React from 'react';
import Header from './components/Header'
import CustomInput from './components/Input'
import CustomList from './components/List'
import ProviderComponent, { Consumer } from './Context'
import styles from './index.module.css'
const App = () => (
<ProviderComponent>
<div className={styles.container}>
<div className={styles.todoList} >
<Header />
<Consumer>
{({ updateContextState }) => (
<CustomInput
type='text'
placeholder='Add New Todo'
updateInputContext={inputState => updateContextState({ textValue: inputState })}
/>
)}
</Consumer>
<CustomList />
</div>
</div>
</ProviderComponent>
)
export default App;
Context API
Redux
Pros
Cons
Pros
Cons