Apollo-Client refetch - TypeError: undefined is not an object

Viewed 1883

I have a flatlist in react-native and I am trying to refetch the data when pulling it down (the native refresh functionality). When I do, I am getting this error:

Typeerror: undefined is not an object

I can't figure out what is going wrong. I am using

  • Expo SDK 38
  • "@apollo/client": "^3.1.3",
  • "graphql": "^15.3.0",

This is my code:

export default function DiscoverFeed({ navigation }) {
  const theme = useTheme();

  const { data, error, loading, refetch, fetchMore, networkStatus } = useQuery(
    GET_RECIPE_FEED,
    {
      variables: { offset: 0 },
      notifyOnNetworkStatusChange: true,
    }
  );

  if (error) return <Text>There was an error, try and reload.</Text>;
  if (loading) return <Loader />;
  if (networkStatus === NetworkStatus.refetch) return <Loader />;

  const renderItem = ({ item }) => {
    return (
      <View style={styles.cardItems}>
        <RecipeCard item={item} navigation={navigation} />
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.safeContainer} edges={["right", "left"]}>
      <FlatList
        style={styles.flatContainer}
        data={data.recipe}
        removeClippedSubviews={true}
        renderItem={renderItem}
        refreshing={loading}
        onRefresh={() => {
          refetch();
        }}
        keyExtractor={(item) => item.id.toString()}
        onEndReachedThreshold={0.5}
        onEndReached={() => {
          // The fetchMore method is used to load new data and add it
          // to the original query we used to populate the list
          fetchMore({
            variables: {
              offset: data.recipe.length,
            },
          });
        }}
      />
    </SafeAreaView>
  );
}

I have a typepolicy like so:

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        recipe: {
          merge: (existing = [], incoming, { args }) => {
            // On initial load or when adding a recipe, offset is 0 and only take the incoming data to avoid duplication
            if (args.offset == 0) {
              console.log("offset 0 incoming", incoming);
              return [...incoming];
            }
            console.log("existing", existing);
            console.log("incoming", incoming);
            // This is only for pagination
            return [...existing, ...incoming];
          },
        },
      },
    },
  },
});

And this is the query fetching the data:

export const GET_RECIPE_FEED = gql`
  query GetRecipeFeed($offset: Int) {
    recipe(order_by: { updated_at: desc }, limit: 5, offset: $offset)
      @connection(key: "recipe") {
      id
      title
      description
      images_json
      updated_at
      dishtype
      difficulty
      duration
      recipe_tags {
        tag {
          tag
        }
      }
    }
  }
`;
0 Answers
Related