Created
March 12, 2019 09:54
-
-
Save sgwilym/a0c1bca61d5cadd35e7bda68222f48f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of what data masking gets us with Relay | |
const AdminList = createFragmentContainer( | |
(props) => <div> | |
{props.admins.map((admin) => <div>{admin.name}</div>)} | |
</div>, | |
{ | |
admins: graphql` | |
fragment AdminList_admins on User @relay(plural: true) { | |
name | |
} | |
` | |
} | |
) | |
const ProjectDetails = createFragmentContainer( | |
(props) => <div> | |
<h1>Project</h1> | |
// If we accidentally pass the wrong object to AdminList, like project.members | |
// AdminList will throw errors when it renders, even though the data has the same shape | |
// thanks to data masking | |
<AdminList admins={props.project.members}/> | |
</div>, | |
{ | |
project: graphql` | |
fragment ProjectDetails_project on Project { | |
admins { | |
... AdminList_admins | |
} | |
members { | |
name | |
} | |
} | |
` | |
} | |
) | |
// ------------------------------------- | |
// Now… | |
// Doing what we can with Apollo + types | |
// and how it isn't quite the same | |
// Importing type generated by Apollo codegen | |
import { AdminUser } from '__generated__/AdminUser.ts'; | |
// A separate fragment to compose into others | |
const AdminFragment = gql` | |
fragment AdminUser on User { | |
name | |
} | |
`; | |
interface AdminListProps { | |
admins: AdminUser[] | |
}; | |
const AdminList = (props) => | |
<div> | |
{props.admins.map((admin) => <div>{admin.name}</div>)} | |
</div> | |
// And the parent component | |
const ProjectDetailsFragment = gql` | |
fragment ProjectDetails on Project { | |
admins { | |
... AdminList_admins | |
} | |
members { | |
name | |
} | |
} | |
${AdminFragment} | |
` | |
const ProjectDetails = (props) => | |
<div> | |
<h1>Project</h1> | |
// If we accidentally pass the wrong object to AdminList | |
// We'll never know because project.members conforms to the type of AdminUser[]! | |
<AdminList admins={props.project.members}/> | |
</div> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment