Issue with State Reset in Next.js Client Component When Triggering Async Function

I am using Next.js 14, and currently on a client component. This component has a multi-step form. In the final step, I trigger a server action to get a response and return feedback.

When the user clicks the Create Account button, they should navigate to the Finalization tab with the index 4, which shows a loading state until the server action returns a response. Then it shows a message to the user.

The process works well when using a fake timeout and fake response to emulate a test. However, when we actually trigger the server action (const data = await register(information);), the function immediately resets the whole component’s state values to their initial values, as if the page was refreshed (but it wasn’t). On the second button click, it works fine.

This is the submitAction function in sign-up-page.tsx‘s Register Form Component:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const submitAction = async (
values: RegistrationDataType['accountSecurity'],
): Promise<ApiResponse | AuthError | undefined> => {
try {
setInformation((prev) => ({
...prev,
accountSecurity: values,
}));
setError(null);
setSuccess(null);
setIsLoading(true);
forward();
const data = await register(information);
if (data.success) {
console.log('Registration successful:', data);
setSuccess(data);
setError(null);
} else if (data.error) {
console.log('Registration error:', data);
setError(data);
setSuccess(null);
} else {
console.log('Registration unknown error:', data);
setError({
code: 'unknown_error',
message: 'An unknown error occurred.',
description: 'Oops! Something went wrong. Please try again.',
status: 400,
});
setSuccess(null);
}
return data;
} catch (error: ApiResponse | AuthError | any) {
console.error(
'%cERROR',
'background: #f43f5e; color: #fff1f2; padding: 2px;',
'An error occurred while registering the user: ',
error,
);
setError({
code: error.code ?? 'unknown_error',
message: error.message ?? 'An unknown error occurred.',
description: 'Oops! Something went wrong. Please try again.',
status: 400,
});
return error;
} finally {
setIsLoading(false);
forward();
}
};
</code>
<code>const submitAction = async ( values: RegistrationDataType['accountSecurity'], ): Promise<ApiResponse | AuthError | undefined> => { try { setInformation((prev) => ({ ...prev, accountSecurity: values, })); setError(null); setSuccess(null); setIsLoading(true); forward(); const data = await register(information); if (data.success) { console.log('Registration successful:', data); setSuccess(data); setError(null); } else if (data.error) { console.log('Registration error:', data); setError(data); setSuccess(null); } else { console.log('Registration unknown error:', data); setError({ code: 'unknown_error', message: 'An unknown error occurred.', description: 'Oops! Something went wrong. Please try again.', status: 400, }); setSuccess(null); } return data; } catch (error: ApiResponse | AuthError | any) { console.error( '%cERROR', 'background: #f43f5e; color: #fff1f2; padding: 2px;', 'An error occurred while registering the user: ', error, ); setError({ code: error.code ?? 'unknown_error', message: error.message ?? 'An unknown error occurred.', description: 'Oops! Something went wrong. Please try again.', status: 400, }); return error; } finally { setIsLoading(false); forward(); } }; </code>
const submitAction = async (
    values: RegistrationDataType['accountSecurity'],
): Promise<ApiResponse | AuthError | undefined> => {
    try {
        setInformation((prev) => ({
            ...prev,
            accountSecurity: values,
        }));

        setError(null);
        setSuccess(null);
        setIsLoading(true);
        forward();

        const data = await register(information);

        if (data.success) {
            console.log('Registration successful:', data);
            setSuccess(data);
            setError(null);
        } else if (data.error) {
            console.log('Registration error:', data);
            setError(data);
            setSuccess(null);
        } else {
            console.log('Registration unknown error:', data);
            setError({
                code: 'unknown_error',
                message: 'An unknown error occurred.',
                description: 'Oops! Something went wrong. Please try again.',
                status: 400,
            });
            setSuccess(null);
        }

        return data;
    } catch (error: ApiResponse | AuthError | any) {
        console.error(
            '%cERROR',
            'background: #f43f5e; color: #fff1f2; padding: 2px;',
            'An error occurred while registering the user: ',
            error,
        );
        setError({
            code: error.code ?? 'unknown_error',
            message: error.message ?? 'An unknown error occurred.',
            description: 'Oops! Something went wrong. Please try again.',
            status: 400,
        });

        return error;
    } finally {
        setIsLoading(false);
        forward();
    }
};

And then passed to the Account Security tab in the following code block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{selectedIndex === 3 && (
<div className='flex flex-col items-center justify-center w-full gap-5'>
<AccountSecurity
accountSecurity={information.accountSecurity}
submitAccountSecurity={submitAction}
isLoading={isLoading}
forward={forward}
backward={backward}
/>
</div>
)}
{selectedIndex === 4 && (
<div className='flex flex-col items-center justify-center w-full gap-5'>
<Finalization
information={information}
isLoading={isLoading}
isSuccess={hasSuccess !== null}
success={hasSuccess}
isError={hasError !== null}
error={hasError}
forward={forward}
backward={backward}
/>
</div>
)}
</code>
<code>{selectedIndex === 3 && ( <div className='flex flex-col items-center justify-center w-full gap-5'> <AccountSecurity accountSecurity={information.accountSecurity} submitAccountSecurity={submitAction} isLoading={isLoading} forward={forward} backward={backward} /> </div> )} {selectedIndex === 4 && ( <div className='flex flex-col items-center justify-center w-full gap-5'> <Finalization information={information} isLoading={isLoading} isSuccess={hasSuccess !== null} success={hasSuccess} isError={hasError !== null} error={hasError} forward={forward} backward={backward} /> </div> )} </code>
{selectedIndex === 3 && (
    <div className='flex flex-col items-center justify-center w-full gap-5'>
        <AccountSecurity
            accountSecurity={information.accountSecurity}
            submitAccountSecurity={submitAction}
            isLoading={isLoading}
            forward={forward}
            backward={backward}
        />
    </div>
)}
{selectedIndex === 4 && (
    <div className='flex flex-col items-center justify-center w-full gap-5'>
        <Finalization
            information={information}
            isLoading={isLoading}
            isSuccess={hasSuccess !== null}
            success={hasSuccess}
            isError={hasError !== null}
            error={hasError}
            forward={forward}
            backward={backward}
        />
    </div>
)}

This is the State Initialisation block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// ? States:
const [hasError, setError] = useState<ApiResponse | AuthError | null>(null);
const [hasSuccess, setSuccess] = useState<ApiResponse | null>(null);
// ? Router:
const router = useRouter();
// * Tabs:
const [selectedIndex, setSelectedIndex] = useState<number>(3);
// ? Information:
const [information, setInformation] = useState<RegistrationDataType>(registrationInitialData);
// - Transition:
const [isPending, startTransition] = useTransition();
// Loading state:
const [isLoading, setIsLoading] = useState(false);
</code>
<code>// ? States: const [hasError, setError] = useState<ApiResponse | AuthError | null>(null); const [hasSuccess, setSuccess] = useState<ApiResponse | null>(null); // ? Router: const router = useRouter(); // * Tabs: const [selectedIndex, setSelectedIndex] = useState<number>(3); // ? Information: const [information, setInformation] = useState<RegistrationDataType>(registrationInitialData); // - Transition: const [isPending, startTransition] = useTransition(); // Loading state: const [isLoading, setIsLoading] = useState(false); </code>
// ? States:
const [hasError, setError] = useState<ApiResponse | AuthError | null>(null);
const [hasSuccess, setSuccess] = useState<ApiResponse | null>(null);

// ? Router:
const router = useRouter();

// * Tabs:
const [selectedIndex, setSelectedIndex] = useState<number>(3);

// ? Information:
const [information, setInformation] = useState<RegistrationDataType>(registrationInitialData);

// - Transition:
const [isPending, startTransition] = useTransition();

// Loading state:
const [isLoading, setIsLoading] = useState(false);

Expected Behavior: When the Create Account button is clicked, it should navigate to the Finalization tab and display the loading state until the server action returns a response.

Actual Behavior: The form resets to the initial state on the first click, as if the page was refreshed. On the second click, it works fine.
Additional Context: The issue does not occur when using a fake timeout and fake response.
Only happens when the server action is triggered.

What I’ve Tried:

  • Ensured state is preserved during the server action.
  • Moved forward() calls to after the server action completes.
  • Verified component structure and keys.

How can I fix this issue?
Any help would be appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật