Last active
March 7, 2021 05:14
-
-
Save rbalicki2/2ac2829aefd8d032e8cb32cd0066bd4e to your computer and use it in GitHub Desktop.
Comparison of Hooks and Container-based Refetching
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
type Props = { | |
comment: CommentBody_comment$key, | |
}; | |
function CommentBody(props: Props) { | |
const [data, refetch] = useRefetchableFragment<CommentBodyRefetchQuery, _>( | |
graphql` | |
fragment CommentBody_comment on Comment | |
@refetchable(queryName: "CommentBodyRefetchQuery") { | |
body(lang: $lang) { | |
text | |
} | |
} | |
`, | |
props.comment, | |
); | |
return <> | |
<CommentText text={data?.text} /> | |
<Button | |
onClick={() => | |
refetch({ lang: 'SPANISH' }, {fetchPolicy: 'store-or-network'}) | |
}> | |
> | |
Translate | |
</Button> | |
</> | |
} |
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
// TodoItem.js | |
import {createRefetchContainer, graphql} from 'react-relay'; | |
class TodoItem extends React.Component { | |
render() { | |
const data = this.props.comment; | |
return ( | |
<> | |
<CommentText text={data?.text} /> | |
<Button | |
onClick={() => | |
this._refetch({ lang: 'SPANISH' }) | |
}> | |
> | |
Translate | |
</Button> | |
</> | |
); | |
} | |
_refetch = (variables) => { | |
this.props.relay.refetch( | |
{ | |
...variables, | |
commentId: this.props.comment.id, // Our refetchQuery needs to know the `itemID` | |
}, | |
null, // We can use the refetchVariables as renderVariables | |
() => { console.log('Refetch done') }, | |
{force: true}, // Assuming we've configured a network layer cache, we want to ensure we fetch the latest data. | |
); | |
} | |
} | |
export default createRefetchContainer( | |
TodoItem, | |
{ | |
comment: graphql` | |
fragment CommentBody_comment on Comment { | |
body(lang: $lang) { | |
text | |
} | |
} | |
` | |
}, | |
graphql` | |
# Refetch query to be fetched upon calling `refetch`. | |
# Notice that we re-use our fragment and the shape of this query matches our fragment spec. | |
query CommentBodyRefetchQuery($lang: String!, $commentId: ID!) { | |
comment: node(id: $commentID) { | |
...CommentBody_comment | |
} | |
} | |
` | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment