Shouldn't I get unique data when I fetch from Github API?

I have an application that display trending repositories from GitHub API.

I am using this function to fetch data, page increments every time I get to the bottom of the page:

function fetchMoreRepos() {
    const url = `https://api.github.com/search/repositories?q=created:>2017-10-22&sort=stars&order=desc&page=${page}`;
    axios.get(url).then(res => setRepos([...repos, ...res.data.items]));
    setPage(page + 1);
    setIsFetching(false);
  } 

I am using this line of code to render every repository:

return repos.map(item => <Repo repo={item} key={item.id} />);

The problem is that sometimes I don't get unique repositories when I get to another page which means key="item.id" is not unique and this gives me a warning in React.

1 answer

  • answered 2019-12-14 11:07 Brett DeWoody

    I'm not entirely sure why some results are appearing across page requests.

    One guess is the order of trending repos is changing, causing a repo at the end of page 1 to drop a few places in the order, and it's pushed to the start of page 2. For example, repo #10 and repo #11 swap places, and if you're requesting 10 results per page, repo #10 is initially in the first page, then pushed to the 2nd page.

    Anyway, a quick solution would be to combine page and item.id for the key. Something like:

    key={`${page}-${item.id}`} 
    

    which should make the key unique.