Developer Stuff:
- Lazily checking for empty objects and arrays
Thursday, November 19, 2020 11:13 AMPro Tip: Don’t.
I’m doing a lot of checking API responses for empty objects or empty arrays in order to render a spinner or some kind of feedback message in the case that the API returns nothing or fails. Handling these cases is pretty important, but what I was doing was fundamentally flawed. I was *only* checking the length of arrays, and for objects I would use the following
{
Object.keys(theObject).length === 0 ?
}: and call it a day.
What’s wrong with that? Well, if your API returns a response message, say something to the effect of
{"result": "FAILURE"}
– it’s an object, and it has a length, so your code is then saying ‘go ahead and render the page’. And then your app crashes.In my case I’m going to check both for an empty object or array, AND for a clear sign that even if I come upon ‘not empty’, that I’m also checking for a clear sign that the response *is not* a green light to render away. Here’s what I landed on for my use case:
const failureCheckObject = (obj) => { const result = Object.entries(obj).filter( ([key, value]) => value === "FAILURE"); return result.length === 0 }
I’m not guaranteeing something like this will solve all of your problems, but I do think it’s wise to walk through your use case and come up with an as-bulletproof-as-possible-in-the-time-available way to check something else about that object or array so that if it kind of actually does meet your definition of ’empty’, you’re handling it well.
- Oh Shit, Git!
Saturday, October 3, 2020 7:04 PMOh Shit, Git is brilliant. Not only is it an incredibly helpful resource for when you step in it with git, like when your eyes were crossed at the end of the day, and you committed to master. What pushes it over the top is that the language *perfectly* captures the way you will feel in those moments, like when you were going too fast, and the thing you tried to do to fix your mistake made it waaay worse.
It’s knowledge and therapy at the same time. If you’re not into the foul language, dangit, git has you covered.