Created
August 25, 2018 05:24
-
-
Save nodkz/ee8bb68da6f72653375feea9e2cd11e8 to your computer and use it in GitHub Desktop.
Relay: unmask fragment by reading data from store
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
function itemTrackingHelper(relayContext, item) { | |
const {title, description} = unmaskFragmentData({ | |
relayContext, | |
relayData: item, | |
fragmentPropName: 'item', | |
fragment: itemTrackingHelperFragment | |
}); | |
} | |
const itemTrackingHelperFragment = graphql` | |
fragment itemTrackingHelper_item on Item { | |
title | |
description | |
} | |
` | |
class MyComponent extends React.Component { | |
handleClick = e => { | |
itemTrackingHelper(this.props.relay, this.props.item) | |
} | |
render() { | |
return <a onClick={this.handleClick}>click here</a>; | |
} | |
} | |
createFragmentContainer(MyComponent { | |
item: graphql` | |
fragment MyComponent_item on Item { | |
...itemTrackingHelper | |
} | |
` | |
}); |
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
import { getSelector } from 'relay-runtime'; | |
export const unmaskFragmentData = ({ relayContext, relayData, fragmentPropName, fragment }) => { | |
let fragmentFunc = fragment[fragmentPropName]; | |
if (typeof fragmentFunc === 'object') { | |
fragmentFunc = fragmentFunc.modern; // compat mode | |
} | |
const selector = getSelector(relayContext.variables, fragmentFunc(), relayData); | |
return relayContext.environment.lookup(selector).data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment