Testing with Jest and Enzyme

I find it hard to do test-first with UI components because I’m always in such a rush to see what the UI will look like. But test-last is better than no test, so let’s test now.

Jest is a unit testing library for Javascript and Enzyme provides an adapter that lets you interact with React components from your test code. We’ll install them using the Yarn package manager.

yarn add -dev jest 
yarn add -dev enzyme enzyme-adapter-react-16

Let’s create a test for our Application component.

import React from 'react'
import {mount} from 'enzyme'
import {configure} from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })

import {Application} from 'application/Application'

describe('The application', () => {
  test('shows the first blog post', () => {
    const component = mount(<Application />)

    expect(component.find('.site-name').text()).toBe('Blogging')
    expect(component.find('.title').text()).toBe('React on Rails')
    expect(component.find('.body').text()).toBe('I can use React with Rails.')
  })
})

mount() will instantiate your component, call all the React lifecycle methods (we’ll cover this later), render it and make the component available for you to write assertions against.

A note about rendering components with Enzyme.

Enzyme has three different methods for rendering a React component:

  • shallow(<C />) renders C but not its child components.
  • mount(<C />) renders C and, recursively, all of its children.
  • render(<C />) renders just the component’s HTML.

It took me a long time to realize that these three methods do totally different things and each have a totally different API. This confused the hell out of me for weeks. Once I realized that, I decided to just stick with mount() unless I have a very good reason to just do a shallow rendering which, so far, is never.

A minor rant about behavioural-style test frameworks

Way back when the first JUnit extensions appeared that let you write tests in pseudo-English so your customer could read them, or maybe even write them, Ron Jeffries said that this was a dead end.

Pseudo-English would always have an uncanny valley feel about it; the tests would be hard to read and harder to write. If programmers write tests, better that they use normal programming conventions that programmers can understand.

I didn’t listen.

After struggling mightily with Fit, Fitnesse, Cucumber, RSpec and God Knows What Else, I decided that maybe Ron had a point and went back to plain JUnit-style assertions.

I don’t know about you, but I find this…

assert_equal 'Blogging', component.find('.site-name').text()

…much easier to read (and write!) than…

expect(component.find('.site-name').text()).toBe('Blogging')

Even better would be…

assert_select('.site-name', 'Blogging')

…and maybe I’ll do something about that one day.

In 20-something years, I’ve never had a customer who was interested in reading — never mind writing — these tests. Just write your best ruby/javascript/whatever and give the tests good names. It will be OK.

Running the tests

We have to tell Jest where to find the tests. Create jest.config.js in the root of your rails app.

// jest.config.js
module.exports = {
  moduleDirectories: [
    "node_modules",
    "app/javascript"
  ],

  rootDir: 'test/javascript',
  clearMocks: true,
  coverageDirectory: "test/results/coverage",
  testMatch: [
    "**/*.test.jsx",
  ],
}

We can run the test with

yarn jest

Continuous Integration

If you sign in to CircleCI via your GitHub account, you can have CircleCI run your tests for you.

Click Set Up Project then follow the instructions to add the CircleCI config file to your project. I won’t repeat them here. If you are lucky, it will work first time.

If you are unlucky like me, you’ll have to copy a working config.xml from somewhere else. You can copy mine if you like. I had to add minitest-ci to my Gemfile to get the test results to show up. I got there in the end.

If you want to be really fancy, you can add the little badge that CircleCI generates to your README.md file.

Here’s mine:

And here it is on GitHub:

https://github.com/klawrence/blogging

Time to write some more code.

In the next instalment, we’ll hook our React component up to use our Rails JSON api.

Introducing React Components

Let’s recap what we’ve done so far.

Let’s work on the React app that will turn our JSON into a beautiful blog post. I like to start with a completely hardcoded UI and work back incrementally from there until it connects with the JSON. We’ll start by deleting the Hello React app and replacing it with the real thing.

If you look under the app/javascript folder, you’ll see two packs.

We’ll delete hello_react.jsx and fix up the application pack to show our blog post. Webpacker gets its knickers in a twist when you delete a pack but stopping and starting webpack-dev-server will usually fix it.

I like to have a top-level Application component that acts as a container for everything else. I also like to group my components on the file system by domain rather than the more usual functional buckets.

Let’s create the Application component and initialize it. I’ll explain what it is doing afterwards.

// javascript/application/Application.jsx
import React from 'react'

export function Application(props) {
  return <div id='application'>
    <h1 className='site-name'>Blogging</h1>
    <h2 className='title'>React on Rails</h2>
    <div className='body'>I can use React with Rails.</div>
  </div>
}

A few things to note if you are new to React.

React has a syntax that looks a lot like HTML for describing views. But it’s not HTML, it’s JSX!

JSX is an extension to Javascript syntax that gets compiled into React components. It’s hard to love JSX and why anyone thought it was a good idea to write code with angle brackets in the 21st century, I have no idea. I thought I was done with remembering to close tags about ten years ago. Maybe I should learn Pug next.

The simplest React component is just a function that returns some JSX. That thing that looks a bit like a <div> tag with an id attribute… that will actually get compiled into code that creates a div component and sets the id property. React components are all about the properties.

You may remember that HTML has a class attribute. But class is a reserved word in Javascript so React uses className instead (React components use camelCase for property names). You’ll remember this after you get it wrong the first 27 times.

The usual trick for bootstrapping a React app is to look for an element in the DOM and then render your React component inside it.

# javascript/application/index.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import {Application} from './Application'

document.addEventListener('DOMContentLoaded', () => {
  const react = document.querySelector('#react')
  ReactDOM.render(
      <Application />,
      react.appendChild(document.createElement('div'))
  )
})

Here’s that div element with id=’react’ on our index page. We don’t need to include the javascript_pack_tag because the application layout file already includes it.

# index.html.erb
<div id='react' />

The last thing is to point the application pack file at our index.jsx.

import 'application'

If you import a folder, Javascript looks for an index.js (or index.jsx) file and runs that. If you have been following along, your javascript folder should look like this:

If you refresh your browser page now and it should look a bit like this:

So that’s our top level Application component done. In the next episode we’ll tidy it up a little and add some tests.

A quick bonus tip before I go.

I like to add an entry to /etc/hosts for each local project. It saves you from resurrecting the ghost favicons from long-forgotten projects and stops your cookies from colliding if you are working on multiple projects at the same time.

# /etc/hosts
127.0.0.1       blogging.local

Rails requires you to declare the host name as a security measure.

# config/environments/development.rb
Rails.application.configure do
  config.hosts << 'blogging.local'
  …

Now I can open the app in the browser with

open http://blogging.local:3000/posts/1.json

Wait a minute! It’s a post, man.

We’ll start with the Post model first. I’ll keep the commentary to a minimum because you know this stuff already.

rails generate model Post title:string body:text
rails db:migrate

We’ll need a test framework. I like Minitest.

# Gemfile 
gem 'minitest', group: :test
bundle install

I use TDD but you can do whatever you like. I’m not your dad.

I’ll fast-forward through the details.

require 'test_helper'
class PostTest < ActiveSupport::TestCase
  test 'a post has a title and a body' do
    post = Post.create! title: 'The title', body: 'The body.'
    assert_equal 'The title', post.title
    assert_equal 'The body.', post.body
  end
end
rails test

.E

Error:
PostsControllerTest#test_should_get_index:
NameError: undefined local variable or method `posts_index_url' for #<PostsControllerTest:0x00007f8939850650>
    test/controllers/posts_controller_test.rb:5:in `block in <class:PostsControllerTest>'

PostTest passes already but PostControllerTest is failing because the path is wrong. Let’s fix that.

require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
  test 'should get index' do
    get posts_url
    assert_response :success
  end
end
rails test

# Running:

..

Finished in 0.382970s, 5.2223 runs/s, 7.8335 assertions/s.
2 runs, 3 assertions, 0 failures, 0 errors, 0 skips

Our React app is going to need some JSON. Let’s add a show action to PostsController.

require 'test_helper'
class PostsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @post = Post.create! title: 'The title', body: 'The body.'
  end

  test 'fetch a post as json' do
    get post_url(@post, format: :json)
    assert_response :success

    json = JSON.parse response.body, symbolize_names: true
    assert_equal @post.id, json[:id]
    assert_equal 'The title', json[:title]
    assert_equal 'The body.', json[:body]
  end
end
# PostsController.rb
class PostsController < ApplicationController
  before_action :set_post, only: :show
  
  private
  def set_post
    @post = Post.find params[:id]
  end
end

# views/posts/show.json.jbuilder
json.extract! @post, :id, :title, :body, :created_at, :updated_at

Let’s create a post so we can see what the JSON looks like.

# In the rails console
Post.create! title: 'React on Rails', body: 'I can use React with Rails.'
open http://localhost:3000/posts/1.json

That’s the back-end taken care of. We’ll build a React component to show our post in the next instalment.

From zero to one

I have Ruby v2.6.6 installed using rvm and I’ll use Homebrew to install Node and Yarn on my Mac.

Installing software tends to either go swimmingly or you end up drowning in a Pool of Despair. In the Pool of Despair case, extra instructions don’t seem to help very much so I’ll keep mine to a minimum.

gem install rails
brew install node  # javascript runtime
brew install yarn  # javascript package manager

Yarn is the equivalent of rubygems in the Javascript ecosystem. We’ll use yarn to install node packages.

Open a terminal and go to that favourite part of your hard drive where you keep all your future dreams and create a rails project.

rails new blogging --database=postgresql --webpack=react --skip-turbolinks --skip-spring

I use PostgresSQL because it makes deploying to Heroku easier. Use SQLite or MySQL if you prefer.

I don’t like Turbolinks.

On four Mac Books in a row, Spring always pegs my CPU at 100% and I don’t know why.

–webpack=react will install Webpack and the node packages for React.

Webpack replaces Sprockets for processing Javascript assets but we’ll still use Sprockets for CSS because I haven’t figured out to use Webpack for CSS yet and everyone says it’s complicated.

I’m going to push everything to Github so I can link to the code online. I just created a repository at https://github.com/klawrence/blogging

cd blogging
git init
git add .
git commit -m 'Start blogging!'

git remote add origin https://klawrence@github.com/klawrence/blogging.git
git push -u origin master

If the install gods are on our side we can create the database, start the server and see the happy, happy Welcome to Rails banner.

rails db:create
rails server
open http://localhost:3000/

When we created our Rails project, Webpacker created a HelloReact app. We can use that to test that React installed correctly. We’ll create a posts controller to initialize HelloReact and we’ll set it as the home page in routes.rb.

rails generate controller Posts index
#routes.rb
Rails.application.routes.draw do
  root to: 'posts#index'
  resources :posts
end

Webpacker compiles javascript modules into packs and the javascript_pack_tag method will include your pack on a page. We’ll call it from the index page.

# views/posts/index.html.erb
<%= javascript_pack_tag 'hello_react' %>

Webpacker ships with a utility that rebuilds your packs and refreshes the page whenever you change any Javascript. We’ll run it in a terminal window.

bin/webpack-dev-server

Now, when I go to http://localhost:3000/, I see the message “Hello, React”. I hope you do too.

Everything is set up now and we’re ready to start coding. In the next episode, we’ll show our first blog post.

React on Rails

When I was first learning React I went through about 17 tutorials before I finally grokked what it was all about. Which is weird because React is quite simple really.

I’m gonna build the tutorial that I wished I’d had when I started learning it.

I’ll assume my reader knows Rails very well but knows just enough Javascript to add sprinkles. I won’t try to teach you React, but I’ll point you in the right direction to learn what you need to know.

Let’s do this.

But “Do what?” you may ask?

We are going to build a blogging platform. It’s going to be Rails on the back end and React on the front end. We’re going to test with Minitest, Jest and Enzyme as we go along. We’ll deploy it on Heroku. We’ll use CircleCI for continuous integration.

We are not going to use Redux. I have an idea for a more object-oriented state management system that leverages the rich metadata that Rails already has and, hopefully, avoids all the acres of boilerplate code that every other React tutorial seems to generate. I don’t have a design for this in mind. I’m hoping one will emerge as we go along.

Let’s start with a quick planning session. What do we want our blogging platform to do?

  • An author can publish a blog post.
  • A reader can read a blog post.
  • The home page shows a list of posts, most recent first.
  • An author can edit a blog post.
  • Readers can comment on a post.
  • Comments are held for moderation.
  • The author can approve comments.
  • Notify the author when there are comments.

At some point we’ll want to upload images and have multiple authors and fancy formatting and RSS feeds and other blogphernalia but that list is enough to get us started.

I’ll tackle the second story first because I like to get something working from end to end as quickly as possible and reading a post has fewer moving parts than creating one.

Join me here to get started.

Back in the day…

In the navy, we would have called this a dit.

I did an electronic engineering apprenticeship in the Royal Navy and, in one of our classes, we had to build little circuits with actual transistors and resistors, wires and crocodile clips. We built AND gates and OR gates and XOR gates and NAND gates and all the rest.

File:TTL NAND OC.svg
NAND gate – Michael Frey

In the next class, they gave us little silicon chips that had AND, OR, XOR, etc gates built-in and we had to connect them all together to make adders and accumulators and hooked them up to 7-segment LED displays and switches to make a simple calculator. You can guess what comes next.

half adder circuit using NAND gates only
Half adder using NAND gates only – Nitianabhigyan

First, there was the Limrose Machine that you programmed by the toggling switches on the input port to make binary numbers.

Image
Limrose Machine

Next up was the Zilog Z80 that we programmed in assembly language until finally, they taught us BASIC on a proper (circa 1984) computer.

When I finally made it on to HMS Southampton to do my sea training, I took turns to do watch-keeping in the computer room where there was an enormous (bigger than my living room) Ferranti FM1600-B computer that the ship used for target tracking and fire control.

It was like going back to the Limrose Machine after programming in BASIC.

This computer had 1k of RAM in about a cubic foot of magnetic core and was connected to all the ships systems via synchros. They were mechanical synchros mind you so, every time the gun turned or the radar tracked a target, you’d hear the Zzzzz of the synchros lining up.

The computer had no ROM. Its operating system was stored on 9-hole punched tape on these massive paper spools which the tape reader would dump into a big basket for the computer operator to re-spool by hand ready for next time.

Unfortunately the computer did not know how to read 9-hole tape but there was another spool of 5-hole tape with the instructions. If only the computer knew how to read 5-hole tape…

Fortunately, the computer operator (me!) had memorized the long series of 24 bit instructions to be entered on the bit switches on the panel of the Ferranti that would start the spool spooling.

This is not the computer. This is just the input panel.

When the computer crashed in the middle of the night (which it did, frequently) and the angry captain was calling (SHOUTING!) down from the Ops Room, the poor operator (me!) had to frantically remember the series of instructions to start that 5-hole tape spooling.

1101 0001 1000 1000 1000 1100
1001 0101 1100 0000 1011 1100
0101 1001 1010 1100 1100 1111
1111 0101 1100 1100 1000 1100
0101 0101 1000 1000 1000 1110

Then I had to enter a different series of instructions for the 9-hole tape. Then quickly, re-spool the paper tape in case it crashed again.

Good times.

Ferranti FM1600 B - Computer - Computing History
The computer is that big thing (in several cabinets) in the background. The thing in the foreground is the input panel.
Note the paper tape reader next to the input panel.
Note also the big blue bin where the paper got dumped as it was spooling.

After programming in Ruby and Rails for several years, Javascript and React feels like going back to the Limrose Machine.

React is so much better than Javascript sprinkles in so many ways but I still feel like I am connecting NAND gates with crocodile clips. It feels like there should be another layer of abstraction on top of React/Redux to hide some of the messiness.

Maybe all that stuff is out there and I just have not found it yet?

It started with a rant

I’ve been using React for a while and now that I have got over my disgust for coding with angle brackets, I think it is wonderful.

I’ve built two big sites on Rails over the last few years and the ”sprinkles of Javascript” pattern that Rails wants me to use has grown, both times, into a big ball of javascript mud where it’s hard to figure out where anything is or belongs.

For my last two or three sites I have used React and I don’t want to go back to sprinkles of Javascript. I like the logical flow of react and I love the idea that all of the UI flows out of the current state.

It’s not all roses in React Land though.

The people who set the trends in Javascript have a great tolerance for ugliness and it bothers me that all of the tutorials have you copy-pasting reams of boilerplate code and you have to write a thousand lines of code before you have anything to show for it.

Here’s an example from https://www.robinwieruch.de/react-fetching-data (nothing against this particular example. This is a typical React tutorial.)

import React, { Component } from 'react';
 
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }
 
  componentDidMount() {
    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

render() {
    const { hits } = this.state;
    return (
      <ul>
        {hits.map(hit =>
          <li key={hit.objectID}>
            <a href={hit.url}>{hit.title}</a>
          </li>
        )}
      </ul>
    );
  }
}

It’s easy to understand why the folks at Basecamp prefer their sprinkles of Javascript.

Here’s the (kind of) equivalent code in Rails/haml.

class HitsController < ApplicationController
  def index
    @hits = Hit.all
  end
end

# index.html.haml
%ul
  - @hits.each do |hit|
    %li= link_to hit.title, hit.url

Why does Javascript need so many lines of code? Is it intrinsic to the language or is it that the folks who write it aren’t interested in readability? And who thought it was a good idea to write code in angle brackets?

And that was just the view.

I haven’t figured out state management in React yet and that’s my mission in this series of posts — to find a better to way to hook the view up to a Rails back end. I have no idea whether I will arrive at my destination but I intend to travel well.

In my first React app, I tried to build an object model like I might in an iOS app and I passed a controller down through the view components to handle events. Disaster.

Then I discovered Redux and I used it for the next couple of apps. I felt like I had joined a south sea cargo cult. If React revels in a surfeit of syntax, Redux positively wallows in it. The tutorials never seem to end and I found I had to constantly go back three pages to remind myself of the difference between an action and an action creator.

On page 7 of the tutorial, if your actions and your action creators and your reducers and your selectors and your dumb components and your connected components are all aligned correctly you’ll get a bit of data to appear in a view but I can’t stop thinking the whole time how much easier it would be to just write 5 lines of haml.

When I am learning, I like to have something working with a few lines of code and then to build from there.

The people who invented Redux have mounded Byzantine complexity on top of the ugliness of Javascript. I often wonder what Redux would look like if @dhh had invented it. Could Javascript and React be beautiful like Ruby and Rails?

And finally, a bonus, and no doubt unwarranted, rant about functional programming.

After 30 years of OOP, I struggle a lot with functional programming. It bugs me no end that, in Redux, the things that look a lot like methods are on the other side of the island from where the data lives. It’s as though the cargo cult people discovered that you could throw a message in a bottle into the outgoing tide and it would be received in the next cove on the following Tuesday.

Why not put the methods next to the data that they manipulate? I’m imagining an object-oriented Redux that feels a bit like Active Record. 

So that’s what I’m going to do. Like the final round of Whose Line Is It Anyway?, I’m going to try to sing Redux in the style of @dhh. 

Wish me luck.

Back to Blogging

I was quite active in the XP community in the first few years of the millennium but I’ve have been so focussed on work for so long that I have not had time to think, never mind write.

I picked up Javascript again a couple of years ago after not touching it for 20 years. I have some thoughts that I want to share.

Javascript has changed so much that it was like entering a foreign land. It reminded me a little of that episode of Red Dwarf where Lister and The Cat arrive back in Nodnol after several centuries away and they don’t even recognize the language.

Javascript was like that for me.

I read the other day that no one likes object-oriented programming any more. Perhaps no one ever did, really, and the whole of the last 30 years was just a con trick played on Blub programmers like me by the titans of the software industry.

It is fair to say that, generations later, the idea of organizing your code into larger meaningful objects that model the parts of your problem continues to puzzle programmers. If they are used to top-down programming or functional programming, which treats elements of code as precise mathematical functions, it takes some getting used to. After an initial hype period had promised improvements for modularising and organising large codebases, the idea was over applied. 

I like OOP and, suddenly, I want to write about it.

Here goes…

Meet me in the Middle?

Story so far:

  • We have a Rails back end that can serialize a blog post to JSON.
  • We have a React front end that can render a blog post.

In this instalment, we want to connect the two together. Let’s do a bit of tidying first.

It sucks that our Application component is doing everything. Let’s extract a Post component. Test first.

I’ll start by copy-pasting application/Application.test.jsx to posts/Post.test.jsx and then strip out the non-post stuff.

describe('The post component', () => {
  test('shows a blog post', () => {
    const component = mount(<Post />)
    expect(component.find('.title').text()).toBe('React on Rails')
    expect(component.find('.body').text()).toBe('I can use React with Rails.')
  })
})

I’ll do the same thing with a Post component and check that all the tests still pass.

import React from 'react'

export function Post(_props) {
  return <div className='post'>
    <h2 className='title'>React on Rails</h2>
    <div className='body'>I can use React with Rails.</div>
  </div>
}

Now I’ll change Application to use the Post component and get rid of the duplication.

import React from 'react'
import {Post} from 'posts/Post'

export function Application(_props) {
  return <div id='application'>
    <h1 className='site-name'>Blogging</h1>
    <Post />
  </div>
}

The tests still pass. Refactoring successful. There’s some overlap between Application.test and Post.test but I’m OK with that.

We’re almost ready to hook the Post component up to the backend but there’s one more fake it step we can take on the road to making it. Let’s pass the post data into the Post component so it doesn’t need to concern itself with where its data came from. Small steps are the best steps.

I’m going to introduce a mediating component between Application and Post that will be responsible for fetching the data. I’ll use the convention ConnectedXXX for a component that connects a view to its data provider.

Here it is (the data is still hard coded for the moment).

export function Post({post}) {
  return <div className='post'>
    <h2 className='title'>{post.title}</h2>
    <div className='body'>{post.body}</div>
  </div>
}

export default function ConnectedPost() {
  const post = {
    id: 1,
    title: 'React on Rails',
    body: 'I can use React with Rails.',
  }
  return <Post post={post} />
}

Notice that I used the default modifier when I exported the ConnectedPost. You can export multiple components (or functions or constants or whatever) from each Javascript file but only one of them can be the default.

When you import a component from another file, you can use named imports like this:

// Application.jsx
import {Post} from 'posts/Post'
...
<Post />

If I skip the braces and import the default export (ConnectedPost), I can call it whatever name I like. I’m gonna continue to call it Post (because the caller doesn’t need to know about implementation details like data providers), like this:

// Application.jsx
import Post from 'posts/Post'
...
<Post />

I won’t show the import statements in my code snippets any more unless there is something significant that I want to draw your attention to. The basic rules to remember are:

  • If you use a component from another file, you have to import it.
  • Remember to indicate whether you want the default component or a named component.
  • Import React in any file that uses JSX.

RubyMine takes care of imports for me magically so I am barely aware of them most of the time anyway.

Now that the post object is no longer hard-coded, we can update Post.test.jsx as a unit test for Post and pass the post in from the outside. We’ll test the ConnectedPost separately later.

  const post = {
    id: 1,
    title: 'The title',
    body: 'The body.',
  }

  test('shows a blog post', () => {
    const component = mount(<Post post={post}/>)
    expect(component.find('.title').text()).toEqual('The title')
    expect(component.find('.body').text()).toEqual('The body.')
  })

Before I do the next interesting change I need to introduce some new concepts. Let’s start with class components.

Class components

All of our components so far have been stateless so it makes sense that they are pure functions. We’ll need to maintain state for our ConnectedPost when it retrieves data from the server so we are going to convert it to a class component.

Aside: The React folks have added hooks to allow you to maintain state in a functional component but the whole thing still feels weird to me. I’m sticking with class components for now.

export default class ConnectedPost extends React.Component {
  render() {
    const post = {
      id: 1,
      title: 'React on Rails',
      body: 'I can use React with Rails.',
    }
    return <Post post={post} />
  }
}

This class component is exactly equivalent to the functional component that it replaced with all the rendering logic moved into a method called render().

Functional components are passed their properties as parameters to the render method like this render(props). Class components access their properties through an instance variable: this.props.

Class components give us two new capabilities. The first is state management.

State Management

React gives us a this.state instance variable that lets us keep track of internal changes to a component like when the user checks a box or presses a button. In our case, we are going to keep track of the post that we are fetching from the server.

There are three aspects to state management.

  1. Initialize the state in the constructor.
  2. Access the state in the render() method (and other methods as necessary).
  3. Change the current state with this.setState().

The reason we are letting React manage our state rather than just using an instance variable is to give React the chance to re-render our component every time the state changes.

Let’s look at the first two aspects together. I’ll change the component to initialize the state with an empty post in the constructor and then access that post in the render() method.

export default class ConnectedPost extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      post: {}
    }
  }

  render() {
    const {post} = this.state
    return <Post post={post} />
  }
}

Before I show you how to change the state, let me introduce the second capability of class components.

Lifecycle methods

The second new capability of class components is lifecycle methods. Lifecycle methods get called when a component is initialized or when some external event happens that the component needs to know about. The most important lifecycle method is componentDidMount().

You read about other lifecycle methods in the React documentation.

Let’s use componentDidMount() now to change the state when the component is first mounted.

export default class ConnectedPost extends React.Component {
 ...
  componentDidMount() {
    const post = {
      id: 1,
      title: 'React on Rails',
      body: 'I can use React with Rails.',
    }
    this.setState({post})
  }
}

We’re now exactly back to where we started but now we have a place to call out to the server to fetch out post. Let’s do it.

  componentDidMount() {
    const request = {
      url: 'http://localhost:3000/posts/1.json'
    }

    return axios(request).then(response => {
      const post = response.data
      this.setState({post})
    })
  }

I’m using axios rather than fetch. My reason is lost in the mists of time but I remember that fetch did something weird with 404 errors that I found annoying. Use fetch if you prefer.

We have to install axios with Yarn…

yarn add axios

…and import it at the top of the Post.jsx file.

import * as axios from 'axios'

We are finally displaying an actual blog post that we loaded from the server but the new changes broke our tests.

We’ll fix that tomorrow.