-
Notifications
You must be signed in to change notification settings - Fork 2.7k
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
How to declare fragment in functional component in Typescript? #2722
Comments
My understanding (feedback welcome) is that doing
I'm using typescript and I've decided to opt out of using fragments this way for exactly the reason you detailed above. Instead I have a file devoted to a fragment... file: export const PokemonCardFragment = gql`
fragment PokemonCardPokemon on Pokemon {
id
url
name
}
` Then in your query... const getPokemonCardQuery = gql`
query getPokemonCard($id:ID!){
...PokemonCardPokemon
}
${PokemonCardFragment}
` Lastly pro tip! Include id in your fragment query and anytime that fragment is fetched it will reload all components that use that fragment data. I.E. if you have some mutation
And as long as your mutation returns |
@danielrasmuson's answer in #2722 (comment) is great! Closing - thanks! |
Yeah, we ended up doing pretty much what @danielrasmuson described, except we colocate the fragment with the component, and use default and non-default exports to use this pattern: // In PokemonCard.tsx:
const PokemonCard: SFC = () => <span />;
export default PokemonCard;
export const PokemonCardFragment = gql`
fragment PokemonCardPokemon on Pokemon {
id
url
name
}
`;
// In the caller file:
import PokemonCard, { PokemonCardFragment } from './PokemonCard'; // <-- This is the main difference in usage
const GET_POKEMON_CARD_QUERY = gql`
query getPokemonCard($id: ID!) {
...PokemonCardPokemon
}
${PokemonCardFragment}
`; |
I came across the same issue, one approach is to extend the interface import { FunctionComponent } from 'react'
interface FCWithFragment<E> extends FunctionComponent<E> {
fragment: string
}
type YourComponentProps = {}
export const YourComponent: FCWithFragment<YourComponentProps> = (props) => {
return ...
}
YourComponent.fragment = gql`
...
` |
Is this really necessary? Apollo client hasn't thought of this already? |
@goughjo03 has there been any updates to this. Running across this in my project and wondering if there's a solution |
@josecolella they are planning to develop a |
I can easily declare a fragment in a class component by adding a static method.
What is the best way to do the same in functional component in Typescript and pass the type checking?
// error: 'fragments' does not exist on type 'typeof PokemonCard'
The text was updated successfully, but these errors were encountered: