Skip to content

Instantly share code, notes, and snippets.

@TSMMark
Last active July 26, 2019 04:29
Show Gist options
  • Save TSMMark/456a6268b81a6bba091022360ed1c8e5 to your computer and use it in GitHub Desktop.
Save TSMMark/456a6268b81a6bba091022360ed1c8e5 to your computer and use it in GitHub Desktop.
useSelectedItems
// Default use:
const [selectedMedias, addId, removeId] = useSelectedItems(medias)
// Example of how to select an item
map(medias, ({ id, title }) => <a onClick={() => addId(id)}>{ id } { title }</a>)
// Example of how to deselect an item
map(selectedMedias, ({ id, title }) => <a onClick={() => removeId(id)}>{ id } { title } is selected!</a>)
// Optional Arguments:
// Optional 4th return if you need a list of all selected ids
const [selectedMedias, addId, removeId, allSelectedIds /* (optional) */] = useSelectedItems(medias)
// Optional 2nd arg to decide if the item is selected, if different from { id }. Default if not provided: `(ids, { id }) => ids.include(id)`
const [selectedMedias, addId, removeId] = useSelectedItems(medias, (ids, { someForeignKey }) => ids.include(someForeignKey))
@TSMMark
Copy link
Author

TSMMark commented Jul 10, 2019

Once we agree on an API for multiple selected items, we could have one for single selected item.

@TSMMark
Copy link
Author

TSMMark commented Jul 25, 2019

Would allow us to replace stuff like this:

https://github.com/Vydia/d2/blob/0ddf2b68a511c55a58e75770245b6a2d4cfb99ee/src/screens/Publish/AdditionalServices/template.js#L48

const [networkExtraIdForMoreInfo, setNetworkExtraIdForMoreInfo]: * = useState<?string>()

const networkExtraForMoreInfo: * = useMemo(
  () => find(networkExtras, ({ id }) => id === networkExtraIdForMoreInfo),
  [networkExtras, networkExtraIdForMoreInfo]
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment