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 committed Nov 18, 2024
1 parent 1971781 commit 2057579
Show file tree
Hide file tree
Showing 4 changed files with 74 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 { getCustomerAddresses } from '../page-data';
import { Addresses } from '../_components/address-book';
import { AddressPageLimit, SearchParams } from '../page';

interface DeleteAddressResponse extends State {
addresses?: Addresses;
}

const DeleteCustomerAddressMutation = graphql(`
mutation DeleteCustomerAddressMutation(
Expand All @@ -32,9 +39,10 @@ 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 +61,17 @@ 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 }),
limit: AddressPageLimit.Default,
});

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

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

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

import { ExistingResultType } from '~/client/util';
import { Link } from '~/components/link';
Expand All @@ -12,30 +12,31 @@ import { useAccountStatusContext } from '../../_components/account-status-provid
import { Modal } from '../../_components/modal';
import { deleteAddress } from '../_actions/delete-address';
import { getCustomerAddresses } from '../page-data';
import { SearchParams } from '../page';
import { useRouter } from '~/i18n/routing';

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);

if (submit.status === 'success') {
onDelete((prevAddressBook) =>
prevAddressBook.filter(({ entityId }) => entityId !== addressId),
);
const result = await deleteAddress(addressId, searchParams);

if (result.status === 'success' && result.addresses) {
onDelete(result.addresses);

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

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

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
26 changes: 19 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 @@ -24,13 +26,17 @@ export async function generateMetadata() {
};
}

export enum AddressPageLimit {
Default = 3,
}

export default async function Addresses({ searchParams }: Props) {
const { before, after } = await searchParams;

const data = await getCustomerAddresses({
...(after && { after }),
...(before && { before }),
limit: 10,
limit: AddressPageLimit.Default,
});

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

0 comments on commit 2057579

Please sign in to comment.