首页 > 其他分享 >[Recoil] Optimising API Calls

[Recoil] Optimising API Calls

时间:2022-10-12 01:22:22浏览次数:68  
标签:return label item API Recoil Optimising import const id

Using cache class to reduce API calls

import {Button} from '@chakra-ui/button'
import {Input} from '@chakra-ui/input'
import {Box, Divider, Heading, VStack} from '@chakra-ui/layout'
import React, {useState} from 'react'
import {
    atom,
    atomFamily,
    DefaultValue,
    useRecoilCallback,
    useRecoilState,
    useRecoilValue,
    useResetRecoilState,
} from 'recoil'
import {shoppingListAPI} from './shippingAPI'

type ItemType = {
    label: string
    checked: boolean
}

class CachedAPI {
    cacheItenms: Record<string, ItemType> | undefined

    private async getItems() {
        if (this.cacheItenms) return this.cacheItenms

        this.cacheItenms = await shoppingListAPI.getItems()
        return this.cacheItenms
    }

    async getIds() {
        const items = await this.getItems()
        return Object.keys(items).map((id) => parseInt(id))
    }

    async getItem(id: number) {
        const items = await this.getItems()
        return items[id]
    }
}

const cachedAPI = new CachedAPI()

const idsState = atom<number[]>({
    key: 'ids',
    default: [],
    effects_UNSTABLE: [
        ({setSelf}) => {
            setSelf(cachedAPI.getIds())
        },
    ],
})

const itemState = atomFamily<ItemType, number>({
    key: 'item',
    default: {label: '', checked: false},
    effects_UNSTABLE: (id) => [
        ({onSet, setSelf, trigger}) => {
            setSelf(cachedAPI.getItem(id))

            onSet((item, oldItem) => {
                if (oldItem instanceof DefaultValue && trigger === 'get') return

                if (item instanceof DefaultValue) {
                    shoppingListAPI.deleteItem(id)
                } else {
                    shoppingListAPI.createOrUpdateItem(id, item)
                }
            })
        },
    ],
})

export const AsyncEffects2 = () => {
    const ids = useRecoilValue(idsState)
    const resetList = useResetRecoilState(idsState)
    const nextId = ids.length

    const insertItem = useRecoilCallback(({set}) => (label: string) => {
        set(idsState, [...ids, nextId])
        set(itemState(nextId), {label, checked: false})
    })

    return (
        <Container onClear={() => resetList()}>
            {ids.map((id) => (
                <Item key={id} id={id} />
            ))}
            <NewItemInput
                onInsert={(label) => {
                    insertItem(label)
                }}
            />
        </Container>
    )
}

const Container: React.FC<{onClear: () => void}> = ({children, onClear}) => {
    return (
        <Box display="flex" flexDir="column" alignItems="center" pt={10}>
            <Box width="400px" backgroundColor="yellow.100" p={5} borderRadius="lg">
                <Heading size="lg" mb={4}>
                    Shopping List
                </Heading>
                <VStack spacing={3} divider={<Divider borderColor="rgba(86, 0, 0, 0.48)" />}>
                    {children}
                </VStack>
            </Box>
            <Button variant="link" mt={3} onClick={onClear}>
                Clear list
            </Button>
        </Box>
    )
}

type ItemProps = {
    id: number
}

const Item = ({id}: ItemProps) => {
    const [item, setItem] = useRecoilState(itemState(id))

    return (
        <Box
            rounded="md"
            textDecoration={item.checked ? 'line-through' : ''}
            opacity={item.checked ? 0.5 : 1}
            _hover={{textDecoration: 'line-through'}}
            cursor="pointer"
            width="100%"
            onClick={() => setItem({...item, checked: !item.checked})}
        >
            {item.label}
        </Box>
    )
}

const NewItemInput = ({onInsert}: {onInsert: (label: string) => void}) => {
    const [value, setValue] = useState('')

    return (
        <Input
            value={value}
            placeholder="New item"
            padding={0}
            height="auto"
            border="none"
            _focus={{border: 'none'}}
            _placeholder={{color: 'rgba(86, 0, 0, 0.48)'}}
            onChange={(e) => {
                setValue(e.currentTarget.value)
            }}
            onKeyPress={({key}) => {
                if (key === 'Enter') {
                    onInsert(value)
                    setValue('')
                }
            }}
        />
    )
}

 

标签:return,label,item,API,Recoil,Optimising,import,const,id
From: https://www.cnblogs.com/Answer1215/p/16783155.html

相关文章

  • Flink Table API 的开发步骤
    1.创建TableEnvironmentFlink的TableAPI/SQL的执行入口功能如下:1.1注册Catalog【数据系统实例】1.2在Catalog中注册库和表1.3加载插件模块1.4执行SQL的查询1.......
  • 使用 Stream API 高逼格 优化 Java 代码
    Java8的新特性主要是Lambda表达式和流,当流和Lambda表达式结合起来一起使用时,因为流申明式处理数据集合的特点,可以让代码变得简洁易读放大招,流如何简化代码如果有一个需求,需......
  • 详解ROMA Connect API 流控实现技术
    1、概述ROMA平台的核心系统ROMAConnect源自华为流程IT的集成平台,在华为内部有超过15年的企业业务集成经验。依托ROMAConnect,可以将物联网、大数据、视频、统一通信、GIS等......
  • windows内核Api的学习
    windows内核api就是ntoskrnl.exe导出的函数。我们可以跟调用应用层的api一样,调用内核api。不过内核api需要注意的是,如果函数导出了,并且函数文档化(也就是可以直接在msdn上搜......
  • 用了这个API协作调试工具,忘记了postman
    ​ 什么是ApifoxApifox是一款接口调试一体化工具,同postman相比,Apifox的功能更加全面,Apifox全中文也更适合国人,Apifox的设计逻辑也非常优秀,如果你是一个新手,我会......
  • 常用API
    Math    System    Object Arrays基本类型包装类日期类......
  • 如何通过 API + 快捷指令,3分钟搭建固定资产盘点系统?
    前言 财务本身的工作十分繁忙,月初忙报税、出报表,月末忙结账对数,月中还得处理各种报销、记账、算工资等杂事,终日不是与Excel为伴,就是在去税局的路上。 每个季度、......
  • 如何通过 API + 快捷指令,3分钟搭建活动邀请和签到系统?
    前言 举办活动,要邀请很多宾客。如何对他们做一对一的身份认证?如何群发邮件为他们进行活动邀请和通知?等到活动那天,现场扫码签到入场,你可能需要采购扫码设备或者购买付费......
  • DW CS4 的 jQuery_api_for_dw4插件下载
    最近一直在找jQuery插件,都不能用。今天同事给了一个,发现确实能用,挺方便,放到cnblogs上来,提供下载。也方便自己以后找的麻烦。呵呵。。​ ----------------------------......
  • [Recoil] Intermediate Selectors
     interface:exporttypeElementStyle={position:{top:number;left:number}size:{width:number;height:number}}exporttypeElement={style:......