I've been jumping all over self-invoking functions to assign values lately. It's been especially useful for one project which required checking existence of several different values while processing a render output, and where not creating values unless conditions pass, or in switch statements, is critical to the end result.
I came up with this fun little fetch 1-liner which uses self-invocation (untested, but it should work as I expect);
It's ideal for react-native, but any fetch-api implementation could use it. If the fetch call succeeds and the response can be turned into JSON, then data will be the contents of the response. If there's an error, that'll be console.logged, but the value of data will be undefined.
Why? It's an elegant solution to handling errors independently from your data - you could send your error to state, or logging, or any other source, but only if it fails, whereas if it succeeds, you've got data and can assign it to state and simply check for existence of the value before you start to work with it.
You could definitely split it out to multiple lines for readability without breaking the chain. It's no different from doing the different parts independently either.
3
u/ChronSyn Mar 18 '19
I've been jumping all over self-invoking functions to assign values lately. It's been especially useful for one project which required checking existence of several different values while processing a render output, and where not creating values unless conditions pass, or in switch statements, is critical to the end result.
I came up with this fun little fetch 1-liner which uses self-invocation (untested, but it should work as I expect);
const data = (async () => await (await fetch('http://someurl.com/')).json().catch(e => console.log(e)))();It's ideal for react-native, but any fetch-api implementation could use it. If the fetch call succeeds and the response can be turned into JSON, then
datawill be the contents of the response. If there's an error, that'll be console.logged, but the value ofdatawill be undefined.