Skip to content

Commit

Permalink
fix(core): refresh the entire list of addresses after deleting an add…
Browse files Browse the repository at this point in the history
…ress
  • Loading branch information
bc-yevhenii-buliuk authored and chanceaclark committed Nov 21, 2024
1 parent 6966f19 commit 51c1585
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-feet-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bigcommerce/catalyst-core": patch
---

refresh the entire list of addresses after deleting an address
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import { client } from '~/client';
import { graphql } from '~/client/graphql';

import { State } from '../../settings/change-password/_actions/change-password';
import { Addresses } from '../_components/address-book';
import { SearchParams } from '../page';
import { getCustomerAddresses } from '../page-data';

interface DeleteAddressResponse extends State {
addresses?: Addresses;
}

const DeleteCustomerAddressMutation = graphql(`
mutation DeleteCustomerAddressMutation(
Expand All @@ -32,9 +39,13 @@ const DeleteCustomerAddressMutation = graphql(`
}
`);

export const deleteAddress = async (addressId: number): Promise<State> => {
export const deleteAddress = async (
addressId: number,
searchParams?: SearchParams,
): Promise<DeleteAddressResponse> => {
const t = await getTranslations('Account.Addresses.Delete');
const customerAccessToken = await getSessionCustomerAccessToken();
const { before, after } = searchParams || {};

try {
const response = await client.fetch({
Expand All @@ -53,7 +64,16 @@ export const deleteAddress = async (addressId: number): Promise<State> => {
revalidatePath('/account/addresses', 'page');

if (result.errors.length === 0) {
return { status: 'success', message: t('success') };
const updatedData = await getCustomerAddresses({
...(after && { after }),
...(before && { before }),
});

return {
status: 'success',
message: t('success'),
addresses: updatedData?.addresses || [],
};
}

return {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,47 @@
'use client';

import { useTranslations } from 'next-intl';
import { PropsWithChildren, useState } from 'react';
import { PropsWithChildren, useEffect, useState } from 'react';

import { ExistingResultType } from '~/client/util';
import { Link } from '~/components/link';
import { Button } from '~/components/ui/button';
import { Message } from '~/components/ui/message';
import { useRouter } from '~/i18n/routing';

import { useAccountStatusContext } from '../../_components/account-status-provider';
import { Modal } from '../../_components/modal';
import { deleteAddress } from '../_actions/delete-address';
import { SearchParams } from '../page';
import { getCustomerAddresses } from '../page-data';

export type Addresses = ExistingResultType<typeof getCustomerAddresses>['addresses'];

interface AddressChangeProps {
addressId: number;
isAddressRemovable: boolean;
onDelete: (state: Addresses | ((prevState: Addresses) => Addresses)) => void;
onDelete: (addresses: Addresses) => void;
searchParams: SearchParams;
}

const AddressChangeButtons = ({ addressId, isAddressRemovable, onDelete }: AddressChangeProps) => {
const AddressChangeButtons = ({
addressId,
isAddressRemovable,
onDelete,
searchParams,
}: AddressChangeProps) => {
const { setAccountState } = useAccountStatusContext();
const t = useTranslations('Account.Addresses');

const handleDeleteAddress = async () => {
const submit = await deleteAddress(addressId);
const result = await deleteAddress(addressId, searchParams);

if (submit.status === 'success') {
onDelete((prevAddressBook) =>
prevAddressBook.filter(({ entityId }) => entityId !== addressId),
);
if (result.status === 'success' && result.addresses) {
onDelete(result.addresses);

setAccountState({
status: 'success',
message: submit.message || '',
message: result.message || '',
});
}
};
Expand All @@ -61,16 +67,29 @@ const AddressChangeButtons = ({ addressId, isAddressRemovable, onDelete }: Addre
interface AddressBookProps {
customerAddresses: Addresses;
addressesCount: number;
hasPreviousPage: boolean;
startCursor: string | null;
searchParams: SearchParams;
}

export const AddressBook = ({
children,
addressesCount,
customerAddresses,
hasPreviousPage,
startCursor,
searchParams,
}: PropsWithChildren<AddressBookProps>) => {
const t = useTranslations('Account.Addresses');
const [addressBook, setAddressBook] = useState(customerAddresses);
const { accountState } = useAccountStatusContext();
const router = useRouter();

useEffect(() => {
if (addressBook.length === 0 && hasPreviousPage) {
router.push(`/account/addresses/?before=${startCursor}`);
}
}, [addressBook, hasPreviousPage, startCursor, router]);

return (
<>
Expand Down Expand Up @@ -112,6 +131,7 @@ export const AddressBook = ({
addressId={entityId}
isAddressRemovable={addressesCount > 1}
onDelete={setAddressBook}
searchParams={searchParams}
/>
</li>
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ interface Pagination {
}

export const getCustomerAddresses = cache(
async ({ before = '', after = '', limit = 9 }: Pagination) => {
async ({ before = '', after = '', limit = 10 }: Pagination) => {
const customerAccessToken = await getSessionCustomerAccessToken();
const paginationArgs = before ? { last: limit, before } : { first: limit, after };

Expand Down
22 changes: 15 additions & 7 deletions core/app/[locale]/(default)/account/(tabs)/addresses/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import { TabHeading } from '../_components/tab-heading';
import { AddressBook } from './_components/address-book';
import { getCustomerAddresses } from './page-data';

export interface SearchParams {
[key: string]: string | string[] | undefined;
before?: string;
after?: string;
}

interface Props {
searchParams: Promise<{
[key: string]: string | string[] | undefined;
before?: string;
after?: string;
}>;
searchParams: Promise<SearchParams>;
}

export async function generateMetadata() {
Expand All @@ -30,7 +32,6 @@ export default async function Addresses({ searchParams }: Props) {
const data = await getCustomerAddresses({
...(after && { after }),
...(before && { before }),
limit: 10,
});

if (!data) {
Expand All @@ -43,7 +44,14 @@ export default async function Addresses({ searchParams }: Props) {
return (
<>
<TabHeading heading="addresses" />
<AddressBook addressesCount={addressesCount} customerAddresses={addresses} key={endCursor}>
<AddressBook
addressesCount={addressesCount}
customerAddresses={addresses}
hasPreviousPage={hasPreviousPage}
key={startCursor}
searchParams={{ before, after }}
startCursor={startCursor}
>
<Pagination
className="my-0 inline-flex justify-center text-center"
endCursor={endCursor ?? undefined}
Expand Down

0 comments on commit 51c1585

Please sign in to comment.