vincent15000's avatar

Encountered two children with the same key

Hello,

I'm learning ReactNative and I get this error : Encountered two children with the same key.

I use the same code a in the series here.

https://laracasts.com/series/build-mobile-apps-with-react-native-and-expo/episodes/11

// backend

public function index()
{
    $recipes = Recipe::with('user:id,name')->orderBy('name')->paginate(10);

    return response()->json(compact('recipes'), 200);
}

// frontend

function getRecipes() {
  api
    .get(`recipes?page=${page}`)
    .then(response => {
      if (page == 1) {
        setRecipes(response.data.recipes.data);
      } else {
        setRecipes([...recipes, ...response.data.recipes.data]);
      }
      setIsRefreshing(false);
      setAllRecipesLoaded(response.data.recipes.next_page_url == null);
    })
    .catch(error => {
      setIsRefreshing(false);
    });
}

function handleEndReached() {
  if (!allRecipesLoaded) {
    setPage(page + 1);
    getRecipes();
  }
}

...

<View style={styles.container}>
  <FlatList
    data={recipes}
    renderItem={renderRecipe}
    keyExtractor={recipe => `recipe-${recipe.id.toString()}`}
    refreshing={isRefreshing}
    onRefresh={handleRefresh}
    onEndReached={handleEndReached}
  />
</View>

I have checked and I don't notice any duplicate key.

What could be the origin of this problem ?

Thanks for your help.

Vincent

0 likes
2 replies
jlrdw's avatar

I don't know all the code but make sure to use a unique id in any iterations you perform.

1 like
Niush's avatar
Niush
Best Answer
Level 50

May be because a new Recipe was added before paginating to next page? Causing the same id to be pushed back to next page? Try with Cursor Pagination.

Or do like this instead:

keyExtractor={(recipe, index) => `recipe-${index}-${recipe.id.toString()}`}
2 likes

Please or to participate in this conversation.