summaryrefslogtreecommitdiff
path: root/src-migrate/modules/cart/components/ItemSelect.tsx
blob: b904a1de7eda9ba6f0b3fc69a72b36a147935732 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Checkbox, Spinner } from '@chakra-ui/react'
import React, { useState } from 'react'

import { getAuth } from '~/libs/auth'
import { CartItem } from '~/types/cart'
import { upsertUserCart } from '~/services/cart'

import { useCartStore } from '../stores/useCartStore'

type Props = {
  item: CartItem
}

const CartItemSelect = ({ item }: Props) => {
  const auth = getAuth()
  const { loadCart } = useCartStore()

  const [isLoad, setIsLoad] = useState<boolean>(false)

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (typeof auth !== 'object') return

    setIsLoad(true)
    await upsertUserCart({
      userId: auth.id,
      type: item.cart_type,
      id: item.id,
      qty: item.quantity,
      selected: e.target.checked
    })
    await loadCart(auth.id)
    setIsLoad(false)
  }

  return (
    <div className='w-6 my-auto'>
      {isLoad && (
        <Spinner className='my-auto' size='sm' />
      )}

      {!isLoad && (
        <Checkbox
          borderColor='gray.600'
          colorScheme='red'
          size='lg'
          isChecked={item.selected}
          onChange={handleChange}
        />
      )}
    </div>
  )
}

export default CartItemSelect