You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We developed the code to apply a discount in the cart. I would normally put in a pull request for this type of thing, but our code now has so many conflicts, it would be too complicated. I figured I'd just post the basic code here and hopefully it will help people who are looking to get this functionality. Adapt to your base code, obviously.
exportasyncfunctionapplyDiscount(prevState: any,formData: FormData){//console.log ("Form Data", formData)constcartId=cookies().get('cartId')?.value;if(!cartId){return'Missing cart ID';}constschema=z.object({discountCode: z.string().min(1),});constparse=schema.safeParse({discountCode: formData.get("discountCode"),});if(!parse.success){return"Error applying discount. Discount code required.";}constdata=parse.data;letdiscountCodes=[];// Create a new empty array - actually this array should be the current array of discount codes, but as we only allow one code now, we create an empty arraydiscountCodes.push(data.discountCode);// Push the string into the array// Ensure the discount codes are unique - this is not really necessary now, because we are only using one codeconstuniqueCodes=discountCodes.filter((value,index,array)=>{returnarray.indexOf(value)===index;});try{awaitupdateDiscounts(cartId,uniqueCodes);//close cart and have tooltip for crevalidateTag(TAGS.cart);}catch(e){return'Error applying discount';}}exportasyncfunctionremoveDiscount(prevState: any,payload: {discount: string;discounts: string[];}){//console.log ("payload", payload)constcartId=cookies().get('cartId')?.value;if(!cartId){return'Missing cart ID';}constcode=payload?.discountconstcodes=payload?.discounts??[]//the entire array of discountsif(!code){return"Error removing discount. Discount code required.";}letdiscountCodes=codes;//remove the code from the array and return the arrayletnewCodes=discountCodes.filter(item=>item!==code);try{awaitupdateDiscounts(cartId,newCodes);//close cart and have tooltip for crevalidateTag(TAGS.cart);}catch(e){return'Error applying discount';}}
Add a Form Component in your Modal for the cart that is something like this (we use Shadcn, so many our components come from there)
functionSubmitButton(props: Props){const{ pending }=useFormStatus();constbuttonClasses='mt-3 inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-9 rounded-md px-3';constdisabledClasses='cursor-not-allowed opacity-60 hover:opacity-60';constmessage=props?.message;return(<>{message&&(<AlertclassName="my-5"variant="destructive"><ExclamationTriangleIconclassName="mr-2 h-4 w-4"/><AlertTitle>{message}</AlertTitle></Alert>)}{pending ? "" : <inputtype="text"name="discountCode"placeholder="Discount code"required/>}<buttononClick={(e: React.FormEvent<HTMLButtonElement>)=>{if(pending)e.preventDefault();}}aria-label="Add Discount Code"aria-disabled={pending}className={clsx(buttonClasses,{'hover:opacity-90': true,[disabledClasses]: pending})}><divclassName="w-full">{pending ? <LoadingDotsclassName="bg-secondary text-white mb-3"/> : null}</div>{pending ? '' : 'Apply Discount'}</button></>);}exportfunctionApplyCartDiscount({ cart }: {cart: Cart}){const[message,formAction]=useFormState(applyDiscount,null);//console.log('Cart Discount Codes', cart?.discountCodes);//filter the discount codes to remove those where applicablce is false and then jsut get the code in array//if we have a discount code we don't show the formconstfilteredCodes=cart?.discountCodes&&cart?.discountCodes.length
? cart?.discountCodes.filter((code)=>code.applicable).map((code)=>code.code)
: [];return(<>{filteredCodes&&filteredCodes.length>0 ? (<div>{filteredCodes.map((code,index)=>(<Badgekey={index}variant="secondary"><TagIconclassName="mr-2 inline-block h-5 w-5"/>{code}<DeleteDiscountButtonitem={code}items={filteredCodes}/></Badge>))}</div>) : (<formaction={formAction}><SubmitButtonmessage={message}/><paria-live="polite"className="sr-only"role="status">{message}</p></form>)}</>);}
We developed the code to apply a discount in the cart. I would normally put in a pull request for this type of thing, but our code now has so many conflicts, it would be too complicated. I figured I'd just post the basic code here and hopefully it will help people who are looking to get this functionality. Adapt to your base code, obviously.
The text was updated successfully, but these errors were encountered: