When working on a part of a user interface I like to constantly try to think about potential bugs that could occur, potentially when looking at taking input from users. Most components that take input will have code to prevent invalid input and bugs and you can’t ever avoid this, but sometimes the right data structure can remove the amount of bugs you’ll have to write code to deal with.
To demonstrate this we’ll be working today with a component that lets a user tag something with tags. The GIF below shows two versions; the first has a bug and the second doesn’t. We’ll talk about why in just a moment…
The great thing is that the second example has no code to explicitly deal with that bug; it uses a more appropriate data structure that makes this bug impossible.
Working with sets
Rather than create my tags state as an array, I instead use a set. You initialise a set by giving it an array of items:
Be careful, new Set('react') gives you a set with 5 items; r, e, and so on. You probably want new Set(['react']) 👍.
You add an item to a set by calling the add method:
constnames=newSet()names.add('jack')names.add('jack')// does nothing!
Be careful though: adding to a set mutates the set. When working with React you typically want to avoid mutating data and instead create new instances. You could use a library such as Immer to make this easier, or pass the set into the Set constructor:
constnames=newSet(['alice'])constnewNames=newSet(names)newNames.add('bob')// newNames = alice, bob// but names is left alone
Using this within our Tags component looks like so:
This is easily solved by converting a set to an array. You can use the spread operator to do this, or use Array.from. Either works:
constset=newSet(['alice'])[...set]// works!Array.from(set)// also works!
I tend to prefer [...set] as it’s cleaner, but this is personal preference so pick your favourite.
Bug avoided! 🐛
Swapping our data structure from an array to a set has completely removed the ability for the user to ever enter duplicates because the data structure forbids it. This means we don’t have to write code to filter duplicates our, and that we don’t have to write tests for it (I wouldn’t test something that’s provided natively by the language) and we can focus on all the other concerns this component has.
Whenever you’re working with some data that has some validation requirements or constraints it’s a good idea to pause and think if you could use a data structure that helps provide some of those constraints out the box with no extra effort on your part.
At Marketing Solution Australia we strive to deliverer elegant responsive websites for your business integrated with our personal SEO Optimization package to bring your pages on the first page of Google.