Skip to content

Commit

Permalink
Merge pull request #53323 from callstack-internal/feature/202-eslint-…
Browse files Browse the repository at this point in the history
…rule-stop-usage-init-function-use-state

Use initializer callbacks for useState
  • Loading branch information
mountiny authored Dec 4, 2024
2 parents aa55b4d + 0fcef73 commit b16d7c1
Show file tree
Hide file tree
Showing 11 changed files with 16 additions and 28 deletions.
4 changes: 2 additions & 2 deletions src/components/DatePicker/CalendarPicker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ function CalendarPicker({
const {preferredLocale, translate} = useLocalize();
const pressableRef = useRef<View>(null);

const [currentDateView, setCurrentDateView] = useState(getInitialCurrentDateView(value, minDate, maxDate));
const [currentDateView, setCurrentDateView] = useState(() => getInitialCurrentDateView(value, minDate, maxDate));

const [isYearPickerVisible, setIsYearPickerVisible] = useState(false);

const minYear = getYear(new Date(minDate));
const maxYear = getYear(new Date(maxDate));

const [years, setYears] = useState<CalendarPickerListItem[]>(
const [years, setYears] = useState<CalendarPickerListItem[]>(() =>
Array.from({length: maxYear - minYear + 1}, (v, i) => i + minYear).map((year) => ({
text: year.toString(),
value: year,
Expand Down
2 changes: 1 addition & 1 deletion src/components/VideoPlayer/BaseVideoPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function BaseVideoPlayer({
const [isEnded, setIsEnded] = useState(false);
const [isBuffering, setIsBuffering] = useState(true);
// we add "#t=0.001" at the end of the URL to skip first milisecond of the video and always be able to show proper video preview when video is paused at the beginning
const [sourceURL] = useState(VideoUtils.addSkipTimeTagToURL(url.includes('blob:') || url.includes('file:///') ? url : addEncryptedAuthTokenToURL(url), 0.001));
const [sourceURL] = useState(() => VideoUtils.addSkipTimeTagToURL(url.includes('blob:') || url.includes('file:///') ? url : addEncryptedAuthTokenToURL(url), 0.001));
const [isPopoverVisible, setIsPopoverVisible] = useState(false);
const [popoverAnchorPosition, setPopoverAnchorPosition] = useState({horizontal: 0, vertical: 0});
const [controlStatusState, setControlStatusState] = useState(controlsStatus);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Debug/DebugDetailsDateTimePickerPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function DebugDetailsDateTimePickerPage({
}: DebugDetailsDateTimePickerPageProps) {
const {translate} = useLocalize();
const styles = useThemeStyles();
const [date, setDate] = useState(DateUtils.extractDate(fieldValue));
const [date, setDate] = useState(() => DateUtils.extractDate(fieldValue));
return (
<ScreenWrapper testID={DebugDetailsDateTimePickerPage.displayName}>
<HeaderWithBackButton title={fieldName} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function DebugReportActionCreatePage({
const styles = useThemeStyles();
const [session] = useOnyx(ONYXKEYS.SESSION);
const [personalDetailsList] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
const [draftReportAction, setDraftReportAction] = useState<string>(getInitialReportAction(reportID, session, personalDetailsList));
const [draftReportAction, setDraftReportAction] = useState<string>(() => getInitialReportAction(reportID, session, personalDetailsList));
const [error, setError] = useState<string>();

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function DebugTransactionViolationCreatePage({
const {translate} = useLocalize();
const styles = useThemeStyles();
const [transactionViolations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`);
const [draftTransactionViolation, setDraftTransactionViolation] = useState<string>(getInitialTransactionViolation());
const [draftTransactionViolation, setDraftTransactionViolation] = useState<string>(() => getInitialTransactionViolation());
const [error, setError] = useState<string>();

const editJSON = useCallback(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ function ReimbursementAccountPage({route, policy}: ReimbursementAccountPageProps
which acts similarly to `componentDidUpdate` when the `reimbursementAccount` dependency changes.
*/
const [hasACHDataBeenLoaded, setHasACHDataBeenLoaded] = useState(reimbursementAccount !== CONST.REIMBURSEMENT_ACCOUNT.DEFAULT_DATA && isPreviousPolicy);
const [shouldShowContinueSetupButton, setShouldShowContinueSetupButton] = useState(getShouldShowContinueSetupButtonInitialValue());
const [shouldShowContinueSetupButton, setShouldShowContinueSetupButton] = useState(() => getShouldShowContinueSetupButtonInitialValue());

const handleNextNonUSDBankAccountStep = () => {
switch (nonUSDBankAccountStep) {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/home/report/ReportActionsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ function ReportActionsList({
const reportScrollManager = useReportScrollManager();
const userActiveSince = useRef<string>(DateUtils.getDBTime());
const lastMessageTime = useRef<string | null>(null);
const [isVisible, setIsVisible] = useState(Visibility.isVisible());
const [isVisible, setIsVisible] = useState(Visibility.isVisible);
const isFocused = useIsFocused();

const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID ?? -1}`);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/iou/request/step/IOURequestStepAttendees.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function IOURequestStepAttendees({
}: IOURequestStepAttendeesProps) {
const isEditing = action === CONST.IOU.ACTION.EDIT;
const [transaction] = useOnyx(`${isEditing ? ONYXKEYS.COLLECTION.TRANSACTION : ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID || -1}`);
const [attendees, setAttendees] = useState<Attendee[]>(TransactionUtils.getAttendees(transaction));
const [attendees, setAttendees] = useState<Attendee[]>(() => TransactionUtils.getAttendees(transaction));
const previousAttendees = usePrevious(attendees);
const {translate} = useLocalize();
const [violations] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`);
Expand Down
22 changes: 5 additions & 17 deletions src/pages/settings/Profile/CustomStatus/StatusClearAfterPage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import {useOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import FormProvider from '@components/Form/FormProvider';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
Expand All @@ -19,7 +18,6 @@ import * as ValidationUtils from '@libs/ValidationUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';

type CustomStatusTypes = ValueOf<typeof CONST.CUSTOM_STATUS_TYPES>;

Expand All @@ -30,13 +28,6 @@ type StatusType = {
isSelected: boolean;
};

type StatusClearAfterPageOnyxProps = {
/** User's custom status */
customStatus: OnyxEntry<OnyxTypes.CustomStatusDraft>;
};

type StatusClearAfterPageProps = StatusClearAfterPageOnyxProps;

/**
* @param data - either a value from CONST.CUSTOM_STATUS_TYPES or a dateTime string in the format YYYY-MM-DD HH:mm
*/
Expand Down Expand Up @@ -80,14 +71,15 @@ const useValidateCustomDate = (data: string) => {
return {customDateError, customTimeError, validateCustomDate};
};

function StatusClearAfterPage({customStatus}: StatusClearAfterPageProps) {
function StatusClearAfterPage() {
const styles = useThemeStyles();
const {translate} = useLocalize();
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const clearAfter = currentUserPersonalDetails.status?.clearAfter ?? '';
const [customStatus] = useOnyx(ONYXKEYS.CUSTOM_STATUS_DRAFT);

const draftClearAfter = customStatus?.clearAfter ?? '';
const [draftPeriod, setDraftPeriod] = useState(getSelectedStatusType(draftClearAfter || clearAfter));
const [draftPeriod, setDraftPeriod] = useState(() => getSelectedStatusType(draftClearAfter || clearAfter));
const statusType = useMemo<StatusType[]>(
() =>
Object.entries(CONST.CUSTOM_STATUS_TYPES).map(([key, value]) => ({
Expand Down Expand Up @@ -222,8 +214,4 @@ function StatusClearAfterPage({customStatus}: StatusClearAfterPageProps) {

StatusClearAfterPage.displayName = 'StatusClearAfterPage';

export default withOnyx<StatusClearAfterPageProps, StatusClearAfterPageOnyxProps>({
customStatus: {
key: ONYXKEYS.CUSTOM_STATUS_DRAFT,
},
})(StatusClearAfterPage);
export default StatusClearAfterPage;
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function CardSection() {
Navigation.navigate(ROUTES.SEARCH_CENTRAL_PANE.getRoute({query}));
}, []);

const [billingStatus, setBillingStatus] = useState<BillingStatusResult | undefined>(CardSectionUtils.getBillingStatus(translate, defaultCard?.accountData ?? {}));
const [billingStatus, setBillingStatus] = useState<BillingStatusResult | undefined>(() => CardSectionUtils.getBillingStatus(translate, defaultCard?.accountData ?? {}));

const nextPaymentDate = !isEmptyObject(privateSubscription) ? CardSectionUtils.getNextBillingDate() : undefined;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function TransactionStartDateStep() {

const [dateOptionSelected, setDateOptionSelected] = useState(data?.dateOption ?? CONST.COMPANY_CARD.TRANSACTION_START_DATE_OPTIONS.FROM_BEGINNING);
const [isModalOpened, setIsModalOpened] = useState(false);
const [startDate, setStartDate] = useState(format(new Date(), CONST.DATE.FNS_FORMAT_STRING));
const [startDate, setStartDate] = useState(() => format(new Date(), CONST.DATE.FNS_FORMAT_STRING));

const handleBackButtonPress = () => {
if (isEditing) {
Expand Down

0 comments on commit b16d7c1

Please sign in to comment.