In this chapter, we will show you the usage of the library by adding Deviation to the example Counter App.
Create a Counter App
To create a counter app, first we will create a CounterApp
that hold the Counter
component:
Copy import { Counter } from './Counter'
export class CounterApp extends React . Component {
render () {
return (
< Counter />
)
}
}
And then we create the Counter
component that render the counter and hold the counter state:
Copy export class Counter extends React . Component {
state = {
counter : 0
}
decrement = () => {
this .setState (({ counter }) => ({ counter : counter - 1 }))
}
increment = () => {
this .setState (({ counter }) => ({ counter : counter + 1 }))
}
render () {
return (
< div >
< p > Counter : < b >{this.state.counter} </ b > </ p >
< button onClick = {this.decrement} > Decrement </ button >
< button onClick = {this.increment} > Increment </ button >
</ div >
)
}
}
Now, we can mount the CounterApp
to ReactDOM
so that the counter app can run:
Copy import { CounterApp } from './CounterApp'
ReactDOM .render (
< CounterApp /> ,
document .getElementById ( 'root' )
)
Lift the State Up
It's simple to create a CounterApp
with a single state, but when you have to share the state throughout your app, you will need to Lift the State Up . To do that, we will create a CounterStore
that handle store's state and actions:
Copy import { Store } from 'deviation'
export const CounterStore extends Store {
state = {
counter : 0
}
decrement () {
this .setState (({ counter }) => ({ counter : counter - 1 }))
}
increment () {
this .setState (({ counter }) => ({ counter : counter + 1 })
}
}
Then, we need to add the CounterStore
to the provider so that it will initialize and provide the Store throughout your app:
Copy import { Deviation } from 'deviation'
import { CounterApp } from './CounterApp'
ReactDOM .render (
< Deviation providers = {[CounterStore]}>
<CounterApp />
<Deviation />
)
Now, CounterStore
can be access anywhere in our app. We can now lift the state up by removing the component state and replace it with the state and the actions from CounterStore
:
Copy import { Inject } from 'deviation'
import { CounterStore } from './CounterStore'
@ Inject ({
counterStore : CounterStore
})
export class Counter extends React . Component {
render () {
const { counterStore } = this .props
return (
< div >
< p > Counter : < b >{counterStore.state.counter} </ b > </ p >
< button onClick = {counterStore.decrement} > Decrement </ button >
< button onClick = {counterStore.increment} > Increment </ button >
</ div >
)
}
}