useSyncExternalStore

This commit is contained in:
Primakov Alexandr Alexandrovich 2024-11-12 20:06:45 +03:00
parent bbcfef6e23
commit fd0eb66563
9 changed files with 172 additions and 53 deletions

16
lib/store.ts Normal file
View File

@ -0,0 +1,16 @@
export const createStore = (initialState) => {
let state = initialState
const listeners = new Set<() => void>()
return {
getState: () => state,
subscribe: (listener) => {
listeners.add(listener)
return () => {listeners.delete(listener)}
},
setState: (newState) => {
state = newState
listeners.forEach((listener) => listener())
},
}
}

6
src/__data__/context.ts Normal file
View File

@ -0,0 +1,6 @@
import { createContext } from 'react'
export const stars = createContext<{
stars: Record<string, number>
setStar: (userId: string, rate: number) => void
}>(null)

25
src/__data__/users.ts Normal file
View File

@ -0,0 +1,25 @@
import { createStore } from '../../lib/store'
export const users = {
'some-user-id': {
id: 'some-user-id',
name: 'alexandr',
surname: null,
email: null,
rated: 3,
avatar:
'https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash',
friends: [{ id: '2' }],
},
'2': {
id: '2',
name: 'not alexandr',
surname: null,
email: null,
rated: 2,
avatar: 'https://www.gravatar.com/avatar/6e?d=robohash',
friends: [{ id: 'some-user-id' }],
},
}
export const usersStore = createStore(users)

View File

@ -1,16 +1,34 @@
import React from 'react'
import React, { useCallback, useState } from 'react'
import { BrowserRouter } from 'react-router-dom'
import { ChakraProvider } from '@chakra-ui/react'
import { Dashboard } from './dashboard'
import { stars as starsContext } from './__data__/context'
import { users } from './__data__/users'
const App = () => {
const [stars, setStar] = useState(
Object.entries(users).reduce(
(acc, [id, user]) => ({ ...acc, [id]: user.rated }),
{},
),
)
const updateStar = useCallback((userId: string, rate: number) =>
setStar((state) => ({ ...state, [userId]: rate })), [setStar])
return (
<ChakraProvider>
<BrowserRouter>
<Dashboard />
</BrowserRouter>
</ChakraProvider>
<starsContext.Provider
value={{
stars,
setStar: updateStar,
}}
>
<ChakraProvider>
<BrowserRouter>
<Dashboard />
</BrowserRouter>
</ChakraProvider>
</starsContext.Provider>
)
}

View File

@ -27,9 +27,8 @@ export const FormTest = () => {
}, [])
const onSibmit = ({ name, age }) => {
console.log(1111111, name, age)
// console.log(1111111, name, age)
}
console.log(1111111, 22222, watch().name)
return (
<Box

View File

@ -13,11 +13,13 @@ import {
Text,
VStack,
} from '@chakra-ui/react'
import { getFeatures, getAllFeatures } from '@brojs/cli'
import React, { memo, useState } from 'react'
import { getFeatures } from '@brojs/cli'
import React, { memo, useCallback, useContext, useState } from 'react'
import { FormTest } from './from'
import { Stars } from '../stars'
import { stars as starsContext } from '../../__data__/context'
import { useUsers } from '../../hooks'
type User = Record<string, unknown> & {
id: string
@ -29,8 +31,6 @@ type User = Record<string, unknown> & {
const features = getFeatures('nav2')
export const Profile = ({
user,
isLink,
@ -40,7 +40,7 @@ export const Profile = ({
isLink?: boolean
title?: string
}) => {
const [rated, setRated] = useState(user.rated || 0)
// const [rated, setRated] = useState(user.rated || 0)
return (
<Box mt={3} borderWidth="1px" p={3} overflowX="hidden">
@ -60,14 +60,23 @@ export const Profile = ({
{features['stars'] && (
<Stars
count={Number(features['stars']?.value) * 2}
rated={rated}
setRated={setRated}
userId={user.id}
// rated={rated}
// setRated={setRated}
/>
)}
</CardFooter>
</Card>
</Box>
{!isLink && features['buttons'] && <Counter value={rated} setValue={setRated} />}
{!isLink &&
features['buttons'] &&
user.friends?.map((friend) => (
<Counter
key={friend.id}
// value={rated} setValue={setRated}
userId={friend.id}
/>
))}
</Box>
)
}
@ -116,17 +125,44 @@ const Form = memo<{ initialState: string; onSubmit(value: string): void }>(
Form.displayName = 'FormMemo'
const Counter = ({ value, setValue, horiaontal = false }) => {
const Wrapper = horiaontal ? HStack : VStack
const withStars =
(Component) =>
({ userId }) => {
const { stars, setStar } = useContext(starsContext)
const addStar = useCallback(
() => setStar(userId, stars[userId] + 1),
[userId, setStar],
)
const subStar = useCallback(
() => setStar(userId, stars[userId] - 1),
[userId, setStar],
)
return (
<Component
userId={userId}
stars={stars[userId]}
addStar={addStar}
subStar={subStar}
/>
)
}
const Counter = ({ stars, addStar, subStar, userId }) => {
const { rate, setUserRate } = useUsers((state) => state[userId].rated)
console.log(userId)
return (
<Center>
<Wrapper>
<Heading>{value}</Heading>
<VStack>
<Heading>{rate}</Heading>
<Button onClick={() => setValue(value + 1)}>+</Button>
<Button onClick={() => setValue(value - 1)}>-</Button>
</Wrapper>
<Button onClick={() => setUserRate(userId, rate + 1)}>+</Button>
<Button onClick={() => setUserRate(userId, rate - 1)}>-</Button>
</VStack>
</Center>
)
}
const CounterWithStars = withStars(Counter)

View File

@ -1,6 +1,8 @@
import { HStack, Icon } from '@chakra-ui/react'
import { FaRegStar, FaStar } from 'react-icons/fa6'
import React, { useMemo, useState } from 'react'
import { stars } from '../__data__/context'
import { useUsers } from '../hooks'
const useStars = (currentRated, starsCount) => {
const [rated, setRated] = useState(currentRated)
@ -18,27 +20,30 @@ const useStars = (currentRated, starsCount) => {
export const Stars = ({
count,
rated,
setRated,
// rated,
// setRated,
userId,
}: {
count: number
rated: number
setRated: (rate: number) => void
userId: string
// rated: number
// setRated: (rate: number) => void
}) => {
// const {
// stars,
// setRated: starsSetRated
// } = useStars(rated, count)
const { rate, setUserRate } = useUsers(state => state[userId].rated)
return (
<HStack>
{Array.from({ length: count }).map((_, index) =>
index + 1 > rated ? (
index + 1 > rate ? (
<Icon
key={index}
color="orange.400"
cursor="pointer"
onClick={() => setRated(index + 1)}
onClick={() => setUserRate(userId, index + 1)}
>
<FaRegStar />
</Icon>
@ -47,7 +52,7 @@ export const Stars = ({
key={index}
color="orange.400"
cursor="pointer"
onClick={() => starsSetRated(index + 1)}
onClick={() => setUserRate(userId, index + 1)}
>
<FaStar />
</Icon>

31
src/hooks.ts Normal file
View File

@ -0,0 +1,31 @@
import { useEffect, useState, useSyncExternalStore } from 'react'
import { usersStore } from './__data__/users'
export const useUsers = (selector) => {
// const [rate, setRate] = useState(selector(usersStore.getState()))
// useEffect(() => {
// const unsubscribe = usersStore.subscribe(() => {
// setRate(selector(usersStore.getState()))
// })
// return unsubscribe
// }, [])
const rate = useSyncExternalStore(usersStore.subscribe, () =>
selector(usersStore.getState()),
)
return {
rate,
setUserRate: (userId: string, rate: number) =>
usersStore.setState({
...usersStore.getState(),
[userId]: {
...usersStore.getState()[userId],
rated: rate,
},
}),
}
}

View File

@ -1,33 +1,16 @@
import { HStack } from '@chakra-ui/react'
import React from 'react'
import React, { memo } from 'react'
import { Profile } from '../components'
import { users } from '../__data__/users'
const users = {
'some-user-id': {
id: 'some-user-id',
name: 'alexandr',
surname: null,
email: null,
rated: 3,
avatar:
'https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash',
},
'2': {
id: '2',
name: 'not alexandr',
surname: null,
email: null,
rated: 2,
avatar: 'https://www.gravatar.com/avatar/6e?d=robohash',
},
}
export const Friends = () => {
export const Friends = memo(() => {
return (
<HStack>
<Profile user={users['some-user-id']} />
<Profile user={users['2']} />
</HStack>
)
}
})
Friends.displayName = 'memo(Friends)'