Skip to content

Commit

Permalink
Update MST typescript example to use hooks (#15237)
Browse files Browse the repository at this point in the history
1. Switched from class components to functional components with hooks (https://reactjs.org/docs/hooks-effect.html)
2. Removed inject pattern (which is obsolete) in favor of hooks (https://mobx-react.js.org/recipes-migration)
3. Switched to mobx-react-lite
  • Loading branch information
kevinsproles authored Jul 17, 2020
1 parent a475480 commit 5e9f310
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { inject, observer } from 'mobx-react'
import React, { useEffect } from 'react'
import { observer } from 'mobx-react-lite'
import Link from 'next/link'
import React from 'react'
import { IStore } from '../store'
import { IStore, useStore } from '../store'
import Clock from './Clock'

interface IOwnProps {
Expand All @@ -10,42 +10,27 @@ interface IOwnProps {
linkTo: string
}

@inject('store')
@observer
class SampleComponent extends React.Component<IOwnProps> {
public componentDidMount() {
if (!this.props.store) {
return
}
this.props.store.start()
}
const SampleComponent: React.FC<IOwnProps> = observer((props) => {
const { lastUpdate, light, start, stop } = useStore('')

public componentWillUnmount() {
if (!this.props.store) {
return
useEffect(() => {
start()
return () => {
stop()
}
this.props.store.stop()
}
}, [start, stop])

public render() {
if (!this.props.store) {
return <div>Store not defined</div>
}
return (
<div>
<h1>{this.props.title}</h1>
<Clock
lastUpdate={this.props.store.lastUpdate}
light={this.props.store.light}
/>
<nav>
<Link href={this.props.linkTo}>
<a>Navigate</a>
</Link>
</nav>
</div>
)
}
}
return (
<div>
<h1>{props.title}</h1>
<Clock lastUpdate={lastUpdate} light={light} />
<nav>
<Link href={props.linkTo}>
<a>Navigate</a>
</Link>
</nav>
</div>
)
})

export default SampleComponent
2 changes: 2 additions & 0 deletions examples/with-mobx-state-tree-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"dependencies": {
"mobx": "^5.9.0",
"mobx-react": "^5.4.3",
"mobx-react-lite": "^2.0.7",
"mobx-state-tree": "^3.11.0",
"next": "latest",
"react": "16.13.1",
Expand All @@ -17,6 +18,7 @@
},
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.3.0",
"@types/node": "^14.0.23",
"@types/react": "^16.4.12"
},
"license": "ISC"
Expand Down

0 comments on commit 5e9f310

Please sign in to comment.