Adding support for default option

This commit is contained in:
okbel 2021-03-10 16:17:47 -03:00
parent 23af68e0e4
commit 9669c426e0
2 changed files with 16 additions and 15 deletions

View File

@ -1,23 +1,21 @@
import cn from 'classnames'
import Image from 'next/image'
import { NextSeo } from 'next-seo'
import { FC, useState } from 'react'
import { FC, useEffect, useState } from 'react'
import s from './ProductView.module.css'
import { Swatch, ProductSlider } from '@components/product'
import { Button, Container, Text, useUI } from '@components/ui'
import type { Product } from '@commerce/types'
import usePrice from '@framework/product/use-price'
import { useAddItem } from '@framework/cart'
import { getVariant, SelectedOptions } from '../helpers'
import WishlistButton from '@components/wishlist/WishlistButton'
import products from 'framework/bigcommerce/api/catalog/products'
interface Props {
className?: string
children?: any
product: Product
className?: string
}
const ProductView: FC<Props> = ({ product }) => {
@ -29,12 +27,19 @@ const ProductView: FC<Props> = ({ product }) => {
})
const { openSidebar } = useUI()
const [loading, setLoading] = useState(false)
const [choices, setChoices] = useState<SelectedOptions>({
size: null,
color: null,
})
const [choices, setChoices] = useState<SelectedOptions>({})
// Select the correct variant based on choices
useEffect(() => {
// Selects the default option
product.variants[0].options?.forEach((v) => {
setChoices((choices) => ({
...choices,
[v.displayName.toLowerCase()]: v.values[0].label.toLowerCase(),
}))
})
}, [])
console.log(product.variants[0])
const variant = getVariant(product, choices)
const addToCart = async () => {
@ -143,7 +148,6 @@ const ProductView: FC<Props> = ({ product }) => {
className={s.button}
onClick={addToCart}
loading={loading}
disabled={!variant && product.options.length > 0}
>
Add to Cart
</Button>

View File

@ -1,9 +1,6 @@
import type { Product } from '@commerce/types'
export type SelectedOptions = {
size: string | null
color: string | null
}
export type SelectedOptions = Record<string, string | null>
export function getVariant(product: Product, opts: SelectedOptions) {
const variant = product.variants.find((variant) => {