Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change selector return type #482

Merged
merged 4 commits into from
Mar 1, 2024

Conversation

tienifr
Copy link
Contributor

@tienifr tienifr commented Feb 28, 2024

Details

Related Issues

GH_LINK

Automated Tests

Manual Tests

Author Checklist

  • I linked the correct issue in the ### Related Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android / native
    • Android / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
MacOS: Desktop

@tienifr tienifr marked this pull request as ready for review February 28, 2024 10:08
@tienifr tienifr requested a review from a team as a code owner February 28, 2024 10:08
@melvin-bot melvin-bot bot requested review from chiragsalian and removed request for a team February 28, 2024 10:08
@chiragsalian
Copy link
Contributor

Is there an App issue to link to? Even if the change is good is there some issue explaining why this change is needed now?

@youssef-lr
Copy link
Contributor

Context here @chiragsalian, but I think it's good to run this by Callstack (or SWM) first.

@youssef-lr
Copy link
Contributor

Asked here.

@chiragsalian
Copy link
Contributor

Cool, thank you

Comment on lines 107 to 108
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, Partial<KeyValueMapping[TOnyxKey]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, Partial<KeyValueMapping[TOnyxKey]>, TOnyxKey>
Copy link
Contributor

@fabioh8010 fabioh8010 Feb 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, Partial<KeyValueMapping[TOnyxKey]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, Partial<KeyValueMapping[TOnyxKey]>, TOnyxKey>
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>

@tienifr We have two issues here:

  1. By changing TOnyxProps[TOnyxProp] to Partial<KeyValueMapping[TOnyxKey]> we lose all type equality check between the components' OnyxProps and withOnyx mapping, which means that we could type anything in the Onyx prop and the selector wouldn't be able to check if its return type matches with the corresponding Onyx prop.

  2. Also, by doing Partial<KeyValueMapping[TOnyxKey]> you are limiting the selector's return to be an object with optional properties of that Onyx value, which is not always the case.

    When we have a combination of a collection key and a selector, the withOnyx will run selector function for each entry of that collection and build a collection object with the results of all selector executions, for example:

    type ContactMethodDetailsPageOnyxProps = {
        policiesIDs: OnyxCollection<string>;
    };
    
    ...
    
    export default withOnyx<ContactMethodDetailsPageProps, ContactMethodDetailsPageOnyxProps>({
        policiesIDs: {
            key: ONYXKEYS.COLLECTION.POLICY,
            selector: (data) => data?.id ?? '', // this is valid and will make policies return a collection of ids
        },
    })(ContactMethodDetailsPage);

To improve these typings, my suggestion is:

  1. Add this type in lib/types.d.ts which will make possible extracting the value of a Onyx collection:
    ...
    type OnyxCollection<TOnyxValue> = OnyxEntry<Record<string, TOnyxValue | null>>;
    
    /**
     * Utility type to extract `TOnyxValue` from `OnyxCollection<TOnyxValue>`.
     */
    type ExtractOnyxCollectionValue<TOnyxCollection> = TOnyxCollection extends NonNullable<OnyxCollection<infer U>> ? U : never;
    ...
  2. Use it in CollectionMapping:
    /**
     * Represents the mapping options between an Onyx collection key without suffix and the component's prop with all its possibilities.
     */
    type CollectionMapping<TComponentProps, TOnyxProps, TOnyxProp extends keyof TOnyxProps, TOnyxKey extends CollectionKeyBase> = BaseMapping<TComponentProps, TOnyxProps> &
        CollectionBaseMapping<TOnyxKey> &
        (
            | BaseMappingKey<TComponentProps, TOnyxProps, TOnyxProp, TOnyxKey, OnyxCollection<KeyValueMapping[TOnyxKey]>>
            | BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
            | BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
        );

This way we can ensure the type equality checks will still work and get rid of these issues when using the selector. For your case in this discussion, final solution would be like this:

type ContactMethodDetailsPageOnyxProps = {
    ...
    policies: OnyxCollection<Pick<Policy, 'id' | 'ownerAccountID'>>;
};

...

export default withOnyx<ContactMethodDetailsPageProps, ContactMethodDetailsPageOnyxProps>({
    ...
    policies: {
        key: ONYXKEYS.COLLECTION.POLICY,
        selector: (data) => ({id: data?.id ?? '', ownerAccountID: data?.ownerAccountID}),
    },
})(ContactMethodDetailsPage);

@tienifr
Copy link
Contributor Author

tienifr commented Mar 1, 2024

@fabioh8010 I'd love your idea above^. It works for me. Using infer keyword is better. I just updated my PR, can you help take a look at it? Thanks

Comment on lines 96 to 97
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>

You changed the wrong Mapping 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah my fault 🤦‍♂️ .

Comment on lines 107 to 108
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, TOnyxProps[TOnyxProp], TOnyxKey>
| BaseMappingStringKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>
| BaseMappingFunctionKeyAndSelector<TComponentProps, TOnyxProps, ExtractOnyxCollectionValue<TOnyxProps[TOnyxProp]>, TOnyxKey>

@tienifr
Copy link
Contributor Author

tienifr commented Mar 1, 2024

Thanks for pointing that out. I updated the PR @fabioh8010

@youssef-lr
Copy link
Contributor

Thanks for working on this folks! May I ask if we can update the types to accept props? I'm seeing this error when passing the props to the selector, the props should contain the previously loaded keys

Screenshot 2024-03-01 at 13 23 41

@youssef-lr
Copy link
Contributor

youssef-lr commented Mar 1, 2024

Hmm actually it doesn't work at all, not due to TS checks, but I see that we use props here, I wonder what's different?

@fabioh8010
Copy link
Contributor

@youssef-lr Do you mind sharing the code that isn't working? I tested here and the types are correct.

Screenshot 2024-03-01 at 12 39 25

@youssef-lr
Copy link
Contributor

Hm I think the changes in react-native-onyx are not being reflected for me locally, here's what I did:

  1. I checked out this PR in react-native-onyx
  2. I ran npm run build:watch
  3. I checked out @tienifr's PR in App, deleted .cache folder in node_modules
  4. I ran npx link publish ~/Code/Expensidev/react-native-onyx
  5. I ran npm run web

Am I missing something?

@fabioh8010
Copy link
Contributor

@youssef-lr After doing npx link publish ~/Code/Expensidev/react-native-onyx, try accessing node_modules/react-native-onyx/dist/withOnyx.d.ts and node_modules/react-native-onyx/dist/index.d.ts to ensure they are updated. Types might start working after this.

@youssef-lr
Copy link
Contributor

Yeah I was just doing that now

@youssef-lr
Copy link
Contributor

They are updated..maybe it's just an issue with my editor. Thanks for checking!

@youssef-lr
Copy link
Contributor

youssef-lr commented Mar 1, 2024

Any idea why the selector takes a single policy instead of all the policies from the collection? Probably out of scope here, but I was under the assumption the param of the selector should be all of the policies

Edit: I think it has always been like this..I will bring up a discussion in Slack as I'm curious if we'd have a need for a selector returning all policies and then we can use a map to only pass the policies we want to the component. One use case is if a component only needs the user's owned policies

Co-authored-by: Błażej Kustra <46095609+blazejkustra@users.noreply.github.com>
Copy link
Contributor

github-actions bot commented Mar 1, 2024

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@youssef-lr
Copy link
Contributor

I have read the CLA Document and I hereby sign the CLA

@youssef-lr youssef-lr merged commit 0ba1d4c into Expensify:main Mar 1, 2024
4 checks passed
@fabioh8010
Copy link
Contributor

@youssef-lr When we have this combination of a collection key and selector, the selector will actually be executed for each item of the collection, and then a collection is returned to the component. Take a look at this function and where it's used in lib/Onyx.js.

@youssef-lr
Copy link
Contributor

I wonder if we could update that such as if the selector returns null we don't include the item in the final collection?

@fabioh8010
Copy link
Contributor

fabioh8010 commented Mar 1, 2024

Currently, if you make the selector return null (I have to do that assertion due to a limitation with the current solution), the result collection would be like this:

Screenshot 2024-03-01 at 13 22 57
{
    "policy_1576B20B2BA20523": {
        "isFromFullPolicy": false,
        "id": "1576B20B2BA20523",
        "name": "0.7574482937523088",
        "role": "admin",
        "type": "free",
        "owner": "0.3004884578151028",
        "ownerAccountID": 14357020,
        "outputCurrency": "EUR",
        "avatar": "",
        "employeeList": [],
        "isPolicyExpenseChatEnabled": true,
        "lastModified": 1701421196016165,
        "chatReportIDAnnounce": 1038301144060652,
        "chatReportIDAdmins": 5618866612197321
    },
    "policy_4EB3958A3E59A354": null,
    "policy_5D57E1CE8332729C": null,
    "policy_6C774C6E2CC5D5FD": null,
    "policy_9753CC55D5893F78": null,
    "policy_BBEDBB1D8A80E431": null,
    "policy_undefined": null,
    "policy_0": null,
    "policy_9FEECFE647F217AE": null
}

Which you could use it to filter the null values (in case you need the number of the records that were "selected").

Your suggestion makes sense but I don't know how it's the impact of it tbh 😅

@youssef-lr
Copy link
Contributor

So here's a use case I'm thinking of, suppose we have a component that only needs a subset of a collection to subscribe to, we don't want re-renders if other items from that collection changes, I think only passing the items to the component would be beneficial here. Buuut, I suppose filtering out null policies and using useMemo would work the same. Thanks for chiming in!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants