Skip to content

Commit

Permalink
refactor(@rallie/react): refactor the implementation of useBlockState
Browse files Browse the repository at this point in the history
  • Loading branch information
run-nan committed Aug 12, 2023
1 parent da20c33 commit a2385a7
Show file tree
Hide file tree
Showing 4 changed files with 2,195 additions and 2,010 deletions.
2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"url": "https://github.com/ralliejs/rallie/issues"
},
"peerDependencies": {
"@rallie/block": "^0.6.0",
"@rallie/block": ">=0.16.0",
"react": ">=16.8.0"
},
"devDependencies": {
Expand Down
18 changes: 14 additions & 4 deletions packages/react/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
import React from 'react'
import type { BaseBlock, CreatedBlock } from '@rallie/block'

const useForceUpdate = () => {
const [, setState] = React.useState({})
const forceUpdate = React.useCallback(() => {
setState({})
}, [])
return forceUpdate
}

export function useBlockState<T extends BaseBlock<unknown>, U>(
block: T,
getter: (state: T['state']) => U,
deps: any[] = [],
) {
const [value, setValue] = React.useState<U>(() => getter(block.state))
const forceUpdate = useForceUpdate()
const valueRef = React.useRef<U>(getter(block.state))
React.useEffect(() => {
const unwatch = block.watchState(getter).do((val) => {
setValue(() => val)
valueRef.current = val
forceUpdate()
})
return () => {
unwatch()
}
}, [...deps]) // eslint-disable-line react-hooks/exhaustive-deps
return value
}, [forceUpdate, ...deps]) // eslint-disable-line react-hooks/exhaustive-deps
return valueRef.current
}

export function useBlockEvents<T extends BaseBlock<unknown>>(
Expand Down
4 changes: 2 additions & 2 deletions packages/vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
"url": "https://github.com/ralliejs/rallie/issues"
},
"peerDependencies": {
"@rallie/block": "^0.6.0",
"vue": ">=2.0.0"
"@rallie/block": ">=0.16.0",
"vue": ">=2.7.0"
},
"devDependencies": {
"@rallie/block": "workspace:*"
Expand Down
Loading

0 comments on commit a2385a7

Please sign in to comment.