How To Get Variables From package.json In Your JS / TS Code

Let’s say you have a bit of information inside package.json that you’d like to use somewhere in your code. An example of this in my case is the version string which I have to set for Electron to then generate the new file name for the “built” version of my app.

I figured if I’m specifying the version in package.json, I could display that value in the app footer. This would then, hopefully, help with a variety of first step debugging processes / help / support requests. It’s a quick visual check to ensure the user is on the latest version.

Anyway, this is one of them things that doesn’t come up for me that often, and when it does, I tend to forget how to do it.

import { version as appVersion } from '../package.json';

const Footer = () => {
  return (
    <footer>
      <p>
        v{appVersion} © 2019 -{' '}
        {new Date().getFullYear()} A6 Software Ltd. All rights reserved.
      </p>
    </footer>
  );
};

(Ugh, seems WordPress code formatting has some … issues, shall we say, at present)

Pretty straightforward.

package.json is not a special case here, even though it might seem like it would be. This is how you can get a value from any JSON file.

This may not work immediately, it really depends on how your project is set up.

How I Fixed: TypeError: Invalid attempt to destructure non-iterable instance

This morning I hit upon a really annoying problem whilst trying to write a basic test for a React component.

The internals of the component are not important to the issue I was facing.

Here’s the outcome:

 FAIL  src/components/my-component.spec.jsx
  ● MyComponent › should dispatch the expected actions when clicking the important button

    TypeError: Invalid attempt to destructure non-iterable instance

      14 |
    > 15 | const MyComponent = ({ some, props }) => {
         |                                                             ^
      16 |   console.log('wtf', { some, props });
      17 |   const ... // do stuff here
      18 |

      at _nonIterableRest (node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/nonIterableRest.js:2:9)
      at _slicedToArray (node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/slicedToArray.js:8:65)
      at MyComponent (src/components/my-component.jsx:15:61)

What frustrated me was that the first it block was working. And then the second block would not work.

I could xit the first it, and then the second it would work / pass. But together, they would not play nicely.

The reason for this is something that’s caught me out several times previously, but something I keep forgetting about. Here we go:

describe('MyComponent', () => {
  afterEach(() => {
    jest.resetAllMocks();
    cleanup();
  });

The issue is the use of jest.resetAllMocks();.

Here’s what it should be:

describe('MyComponent', () => {
  afterEach(() => {
    jest.clearAllMocks();
    cleanup();
  });

In case you missed it, switch resetAllMocks for clearAllMocks.

The reasoning, in my case is that I had declared a .mockImplementation elsewhere in my test, and a call to resetAllMocks wipes out that mock implementation.

At least, that’s my understanding of it.

For more details see the docs for the difference between resetAllMocks and clearAllMocks.

How I Fixed: React Native – Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

This one had me kicking myself.

What you see on your phone

I really like VSCode for JS projects, but man-oh-mally, on this occasion it bit me. I wonder if I need another plugin, or something?

Bit easier to see in Chrome developer tools debugging session

The error in full for Google searchers:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in _default (at renderApplication.js:35)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:98)
    in RCTView (at View.js:45)
    in View (at AppContainer.js:115)
    in AppContainer (at renderApplication.js:34)

Solving this, for me, was actually really straightforward. The issue was a typo of fail proportions.

I’d been playing around with using functional components with React Native, instead of the more typical (from all the examples I’ve seen anyway) class component approach:

import React from 'react';
import { Text, View  } from 'react-native';

export default App => () => {
  console.log('hi');
  return (
    <View>
      <Text>hello react native!</Text>
    <View>
  )
}

Pretty basic, right? I always feel somehow much worse about myself when my most basic creations fail unexpectedly.

The problem is (as best I can tell) a syntax error. But neither VSCode nor WebStorm flag this up.

Ok, so to put us all out of our misery:

export default App => () => {
# should be:
export default App = () => {

But why doesn’t the IDE flag this?

I’m not sure how this initial fat arrow could ever be valid syntax? I’ve tried playing around in the console and I can’t seem to make it work.

Anyway, hopefully for you, it’s something similar if not identical. Fat fingers, fat arrows.

The 2018 Beginners Guide to Back End (JSON API) + Front End Development

It’s been a few weeks in the making, but I am happy now to reveal my latest course here on CodeReviewVideos:

The 2018 Beginners Guide to Back End (JSON API) + Front End Development.

This course will cover building a JSON-based API with the following back-end stacks:

  1. ‘raw’ Symfony 4 (PHP)
  2. Symfony 4 with FOSRESTBundle (PHP)
  3. API Platform (PHP)
  4. Koa JS (JavaScript / node)

Behat will be used to test all of these APIs. One Behat project, four different API implementations – in two different languages (PHP and JS).

We’re going to be covering the happy paths of GET , POST , PUT , (optionally) PATCH , and DELETE.

We’ll also be covering the unhappy paths. Error handling and display is just as important.

Where possible we’re going to try and use just one Behat feature file. It’s not always possible – the various implementations don’t always want to behave identically.

There’s a ton of good stuff covered in these videos. But the back end is only half the battle.

Whether you want to “catch them all”, or you’re working with a dedicated front-end dev, it’s definitely useful to know the basics of both.

With that in mind, you can pick and choose whether to implement the back-end, or front-end, or both.

If you don’t want to implement a back-end yourself, cloning any of the projects and getting an environment up and running is made as easy as possible by way of Docker. But you don’t need to use Docker. You can bring-your-own database, and do it that way, too.

The Front End

Whatever back end you decide to spin up, the front end should play nicely.

We’re going to implement a few different front-ends. The two I’m revealing today are:

  1. ‘raw’ JavaScript
  2. React

I have plans for a few others, but each implementation is a fair amount of work and I don’t want to over promise at this stage. There’s definitely at least two more coming, but let me first get these two on the site 🙂

The raw JavaScript approach aims to show how things were in the ‘bad old days‘. The days before your package manager  would take up ~7gb of your hard disk with its cache  directory.

The benefit of working this way is that there’s really no extra ‘stuff’ to get in the way. We can focus on making requests, and working with responses.

But that said, this is 2018 and the many modern JavaScript libraries and frameworks are fairly awesome. You’ll definitely get a renewed sense of appreciation for how much easier your life is once you’re comfortable using a library like React, after having done things the hard way.

Again, as mentioned we will cover more than just raw JS and React. Currently each implementation is between ten and fifteen videos. Each video takes a couple of hours to write up, and another couple of hours to record on average. I’m going as fast as I can, and will upload and publish as quickly as possible.

You can watch them as they drop right here.

Site Update

Behind the scenes over the past 10 weeks I have been working on integrating CodeReviewVideos with Braintree.

This is to enable support for PayPal.

I tried to create a ticket for everything I could think of ahead of starting development.

And I added a new ticket for any issue I hit during development. I’m not convinced I tracked absolutely everything, but even so I completely underestimated just how much work would be involved in this feature.

Being completely honest, I have never been more envious of Laravel’s Spark offering. For $99 they get Stripe and Braintree integration, and a whole bunch more. Staggering.

There’s a bunch of other new and interesting features in this release.

I’ve taken the opportunity to migrate from Symfony 3 to Symfony 4 for the API. There’s a bunch of new issues that arose during this transition – I hadn’t given it much prior thought, but with the new front controller (public/index.php) totally broke my Behat (app_acceptance.php) setup.

This work is also enabling the next major feature which I will start work on, once PayPal is live. More on that in my next update.

I appreciate that from the outside looking in, there doesn’t seem to have been a great deal of activity on the site over the last few weeks. I can assure you that behind the scenes, there has never been more activity.

Have A Great Weekend

Ok, that’s about it from me for the moment.

As ever, have a great weekend, and happy coding.

p. s. – I would be extremely grateful if you could help me spread the word by clicking here to tweet about the new course.