sickdyd / react-search-autocomplete

A search box that filters the provided array of objects
https://sickdyd.github.io/react-search-autocomplete
MIT License
220 stars 84 forks source link

Encountered two children with the same key Warning #18

Closed madaher-dev closed 3 years ago

madaher-dev commented 3 years ago

Hello, Thank you for the great component and features. I am trying to search an array that has a name field with duplicates (unique by an _id field) I want the search to list the duplicates but i am getting the following Warning. Is it something wrong i am implementing or the component does not support duplicates in the name key?

Warning: Encountered two children with the same key, rsa-result-undefined. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. in ul (created by Results) in div (created by Context.Consumer) in StyledComponent (created by styled.div) in styled.div (created by Results) in Results (created by ReactSearchAutocomplete)

sickdyd commented 3 years ago

Hello @madaher-dev!

The unique field must be id and not _id. The elements of the array you pass to the component don't have the id field, so it's alaways undefined, therefore you get the warning.

I suppose you are using a MongoDB array of documents. You can re-map them by doing something like:

// An array of documents
const users = [
  {
    _id: 0,
    name: 'sickdyd'
  },
  {
    _id: 1,
    name: 'madaher'
  }
]

// remap them
const usersRemapped = users.map(({ _id, name }) => ({ id: _id, name }))

// if unfamiliar with destructuring
const usersRemapped = users.map(user => ({ id: user._id, name: user.name }))

Let me know if this fixes your issue.

madaher-dev commented 3 years ago

Perfect will do and confirm. Thank you for the quick response. Any plans to add the feature of defining a React component as a result?

sickdyd commented 3 years ago

@madaher-dev You're welcome!

About your question: you mean having a list of components in the list of results rather than just text?

madaher-dev commented 3 years ago

I can confirm that this solved the issue. Yes, a great example is the twitter search (web). You type a user name and in the results you get a component (i assume) with the user photo , name, and handler. This would be so cool!

sickdyd commented 3 years ago

@madaher-dev Sounds like a nice idea. I'll think about it! 🦖