All posts by Sean Dolinar

Automatically Build GatsbyJS Site When Publishing WordPress Post

With a headless WordPress site, you need a way to communicate with the front end when there is a new post. With a AJAX-only site, the API update should be sufficient, but with a Gatsby or other static site, the site has to rebuild with each update. I’ve created a quick plug-in for WordPress on my GitHub. It can also be incorporated into the functions.php of your WordPress

So how to trigger the rebuild?

Build Hook

Netlify makes that easy with build hooks. Build hooks can be created in the site settings menu under Build & Deploy >> Continuous Deployment.

What build hook is just a URL that you sent a POST request to in order to trigger a rebuild. And that can be easily done with JavaScript specifically with jQuery and it’s AJAX methods.

Sending the POST Request

The wp-admin panel runs jQuery so we’ll use it to send the POST request. Below is the JavaScript code that sends the POST request.

Trigger From WordPress

We have code to fire off the POST request, but we also have to attach it to an action. There are a few different ways to do this, the simplest way I found was to attach the POST request to the action of pushing the publish button or the update button. We can do that by putting an event listener on those buttons. The code below does two additional things to the initial AJAX snippet of code.

  • It attaches the POST request to the #publish and #original_publish buttons, which are publish and updates buttons.
  • It also limits the event listener to only the post.php page.

Include the JavaScript in Your WordPress CMS

The final step is to include this JavaScript into the JavaScript files that WordPress runs. We can do that with the admin_enqueue_scripts WordPress action hook.

This takes the JavaScript file and attaches to the post.php and post-new.php pages, so that the script runs when the page loads.

New Blog Front End Using GatsbyJS

If you visit this site often, you might have noticed a layout change this week. I rebuilt the front end of my blog in ReactJS and GatsbyJS. I’ve been wanting to rebuild the front end of the site for a while now, and I didn’t want to start a new project in PHP and try to shoe horn in ReactJS, which is my JavaScript front end library of choice. GatsbyJS was the solution I settled on. The blog now (as of writing this) consists of static files instead of rendering a PHP page every time. I’m going to write more about the entire process. Not all of it was smooth, but I really like the performance and product that this stack has provided so far.

To give you an overview of the tech stack.

  • WordPress is the CMS. I use the same WordPress install I had before, but I’m now using it only as a CMS. The REST API feeds the data into Gatsby.
  • GraphQL is the querying language that Gatsby uses to interface with the WordPress API. It’s pretty fresh at the moment. I found it easy to pick up in a basic, functioning sense. I have yet to set it up or do difficult queries.
  • ReactJS is used to create pages and components for the site. I have a lot to say about React in general, but I’ll save that for other topics. To me, using React in this context of generating static pages made it look like React is an evolved form of HTML.
  • GatsbyJS does A LOT. In short it takes your data with React pages, templates, and components then generates HTML/CSS/JS files for upload to a hosting platform. It also creates service workers and creates “blazing fast” sites. The speed bump alone is worth considering for a WordPress site. Not to mention it gets you out of PHP world.

There are a few downsides, since it’s a static site generator, it takes several minutes for a new build of this site, which is ~80 pages. I do not frequently update the blog, so this isn’t an issue here.

You could also build client-side apps and have dynamic data updated via AJAX calls, so the “static” part of the static site isn’t quite that rigid. You just can’t have a server render pages.

React Context API: Multiple Consumer and Providers

With React’s Context API you are able to use multiple Providers and Consumers using different context instances. This could be useful if you want to separate different data models into distinct parts of your app. For example, you could have a data context and a table context. One context instance could be used to control what data your REST API is sending back, while another instance controls your sorting, paging, etc.

Continuing the extremely simple light bulb example, I’ve decided to build multiple rooms (a living room and a hallway) with some switch wall plates and a light in each room. This should be a familiar setup to anyone who has a three-way switch in their hallway, so you can turn the hallway light off at either end of it. In order to make this, we will create:

  • “Circuits” (context instances) for the living room and the hallway
  • Wall plate components for each room to house light switch components
  • A three-way switch for the hallway light
  • A normal switch for the living room light
  • Light bulbs for each room

Putting that together we get the mini-app below:

The full code is available on my GitHub, but let’s start with the core App component:

app.js 📄

There is a lot of component composition here. We have a WallPlate component for each room along with a component for the room itself which houses the light bulb. We have the two providers wrapping the both rooms with the values defined in terms of the App’s state and a method that can set that state. For this example we are using numbered circuits:

Circuits (Context instances)

  • LightCircuit1 — (Living) Room
  • LightCircuit2 — Hallway

The context instances also correspond to a specific variable in the main app components’s state; once again either 1 or 2. In the interest of being straight forward, each context instance have the different states hardcoded into the Provider’s value. If you were using them to control data and the table view separately the Provider’s initial value object should look demonstrably different from each other, but since this is a just a demonstration, they look similar.

The component of most interest is the WallPlateLivingRoom component. It’s the only component which has multiple consumers. [The rest of the components resemble the last few React Context API examples.]

WallPlateLivingRoom.jsx 📄

I think the Consumer use is pretty straight forward. You need to first use the correct consumer for what you want to do, then pass the context to your child components as you would with just one component. The React docs show nested Consumer components, but they don’t need to be.

This is a simple example, so using Context API like this is overkill, but you can see how you are able to use different context instances within your app. If you have questions about the basics of Context API or are curious about some of the building blocks of code used in this example check out the previous posts on this topic: A Way Too Simple Context API Example, Context API: Three Way Light Switch.

React Context API: Three Way Light Switch

In the Way Too Simple Context API example, we made a simple light switch. This post will show why flux, the single source of truth, and Context API are really useful.

The last post had just two components (not counting the App component): a light switch and light bulb. Here we are going to add a second light switch making this circuit mimic the three-way switch common in many homes.

In this system we want the following to happen:

  • flipping any switch will change the state of the light
  • the “physical” direction of the switch shouldn’t matter

This is meant to represent a switch in real life, and physical switches don’t throw themselves in response to a change in the system. On a web app, you’d most likely want the component’s feedback to change to reflect the state of the app. If you are curious about how three-way switches work in electrical circuits, it’s quite interesting. Unlike the electric circuit, our mini React app has a single source of truth and by manipulating that we can affect the whole system.

Luckily, because of the way we designed the original Context API light switch app, adding another switch is easy enough as putting a second light switch in the App.js file in the three-way-switch branch of the Context API example project.

app.js 📄

We also added a few aesthetic things: the three-way class to remove the “on” / “off” label and another spacer, but to make this work, all that was added was just another LightSwitch component!

The magic is in the flipSwitch: () => this.setState({on: !this.state.on }) function in the Provider that gets passed to the LightSwitch component and run when someone clicks on the component. The flipSwitch function also looks at the App component’s state for the on property, negates it, and then sets it as the negated value creating a toggling effect.

Once again, since this is a simple example, we could accomplish this by lifting up the state and sending it back down with props, but with Context API it doesn’t need that direct chain. LightSwitch can place it in other components (like a Room, LightPlate, etc.) as long as they are children of the Provider.

A Way Too Simple React Context API Example

React’s Context API is convenient built-in state management for React Projects. It has it’s advantages and disadvantages over a library like Redux for sending props and changing the app’s state. I’m going to focus on the advantages of using Context API and getting an overly simple example to work.

The example in this post only has two levels of components, so it is actually advised against by the React documents. If you were actually making an app with this few of components it would be easier just to pass props and lift up state. But let’s figure out how Context API works! Below is a mini React Context API app that is a light bulb and a light switch.

I’m going to assume a few things:

  • a working knowledge of React.
  • familiarity with the single source of truth behind the Flux model in React
  • familiarity with ES6 JavaScript syntax

Also, the full code for the project is at https://github.com/seandolinar/context-api-example, but the code excerpts in the post are only the relevant parts (I left out the import statements, etc.). I made it with create-react-app, which is a pretty good quick start boilerplate for playing around with React without a lot of setup time.

Alright! There are really just three normal React components:

  1. the App
  2. the LightBulb
  3. the LightSwitch

The app’s global state only has the lightbulb on/off, which affects only the display of the LightBulb. And that state can be changed by only the LightSwitch. Overly simple; let’s go through some code!

context.jsx 📄

Alright, this is too simple. We create a context that can be imported into the different the components.

app.js 📄

This object is the heart of the app, so let’s start here. We create a state in the App’s constructor, initially setting the state.on = false. The new part is the LightCircuit.Provider Context API component. It wraps the what would have been the root app component. The value attribute of the Provider is the default/starting value. There are two items in the default context:

  • the App’s state [state]
  • a function for changing the App’s state [flipSwitch()]

This will be passed to any Consumer components like in the LightBulb component.

LightBulb.jsx 📄

This component is just a Context Consumer component, and a div that uses the context’s state. The ({state}) => part of the arrow function destructs the context and only uses the state, which is then used to change the className which controls CSS to show the light bulb is lit or dark. The div that’s inside the consumer component could be any component, composition of components, or even JavaScript.

The annoying thing about Context API is having to pass the context through the arrow function. It creates some JavaScript structure I’m not crazy about since it limits what you can do with the context in that component without additional code.

LightSwitch.jsx 📄

The LightSwitch component does one important thing: it runs flipSwitch() from the context, which in turn changes the state in the top-level App component. We are destructuring the flipSwitch() from the context then putting that into a catch all handelClick() function to run when the button is clicked.

I did add one extra layer on complication, I create an up and down state internal to the switch. Since the circuit doesn’t affect the position of the physical switch in real life, so it shouldn’t here. That is why the extra handleClick() function was made and why the LightSwitch component has its own state.

Conclusion

Hopefully, walking through the simple example with Provider, Consumer and Context can help you get Context API working for your app. Again, this is too simple of a demo, and actually a bad example of how to use it. It works well if the light switch was buried within a hypothetical LightPlate, Wall, Room, and Circuit component. That way you wouldn’t have to lift up state through several layers of components.

My Dead Simple Redux Example

If you are here, I assume you are banging your head against the wall trying to figure out Redux for a React project. If you are looking for a quick start for a React project that has Redux already setup then this is a good boilerplate: http://mikechabot.github.io/react-boilerplate/.

But you are probably still a little confused on how the Redux part of that works…or at least I was. Even the demos on the official Redux site have a lot of complications to illustrate more features, so it takes a while to learn the skeleton structure of the library.

For my example. I’m going to assume a few things:

  • a working knowledge of React.
  • familiarity with the single source of truth behind the Flux model in React
  • a node.js / webpack build environment
  • familiarity with ES6 JavaScript syntax

The example is going to be an on/off switch and a “light bulb” that also has an on/off state. Here is the code and the deployed example. So there will be one action with two values. Dead. Simple. [If you need more complicated examples, please references some of the more involved tutorials. My example is only meant to show the relationship between the components and the parts of redux.]

I’m going to divide this tutorial into two parts: 1.) the Redux parts and 2.) the connection into React components.

Redux

Let’s first look at the three parts of Redux:

  • Store — keeps the single state of truth in its state and dispatches actions
  • Action — the thing that’s dispatched to a reducer
  • Reducer — a function that takes the previous state and the dispatched action and returns a new state

Here is the diagram I use to help me think about what’s happening.

The one thing I want to draw your attention to is the Dispatch() and action part. The action itself isn’t really doing anything. It’s just a JavaScript object. But the dispatch() method within the store is what actuates the entire process, not the action.

So let’s look at the example’s code.

Action

There is nothing special going on here. We are not importing any dependencies. All this is is just a function that returns a JavaScript object like { type: 'FLIP_SWITCH', value: 'off'}. The type property is use by the reducer to determine what type of action is being dispatched. In our simple example the value with be either 'on' or 'off'.

Reducer

Once again there are no dependancies here, so there is nothing special going on here either! The reducer is just a function that takes a state and action as parameters and then does something with those to create a new state. In our case we test the action’s type property to make sure it’s 'FLIP_SWITCH', and if that’s true we set the state to the action’s value. [Either 'on' or 'off'.]

The reducer will return a state to the store.

Store

Alright now we have some fancy dependencies. We use the createStore() from the redux package to create our store. It takes the reducer and the initial state as parameters. Here I set the initial state to 'off' and import the reducer we just made. This is how the store is aware of the reducer.

State
A word about state. In our example we are using a string as the state. But this could be a JS object instead. Most other example will use a JS object as the state.

React

I don’t want to get into React components and all of that stuff. The two components I made for this example are pretty simple and use props and an event listener / handler. The details of the components don’t matter all too much. The interaction of Redux and React come from the connection and the mapping functions.

This the entire app.jsx code. I’ll go through the important parts and it’s not necessarily in order.

connect()

For this App is a React component. What we are doing is connecting the dispatch and state from Redux to our App component. The mapStateToProps and mapDispatchToProps are both functions.

mapStateToProps

mapStateToProps takes the state from the store and passes into the connected component’s props. In this case we take the state which is a string and pass it into App‘s power prop. It returns a JavaScript object that it merges into the components props.

mapDispatchToProps

So we can get the state into the component but how to we actuate change in the store? With dispatch! So what we are doing here passing a function to the components props that runs a dispatch() method inside of it. Here we are passing the a function that takes the on/off value into a flipSwitch action which is dispatched to the reducer which then updates the store’s state, which because of the mapStateToProps function, updates the components power props.

Provider

This isn’t that interesting, but it’s necessary. To make it all work we place our ConnectedApp component inside a Provider component which deals with the store.

App

Let’s finally look at the App component. This is what’s connected to the store and the mapStateToProps and mapDispatchToProps functions. You can see the power props are passed to the LightBulb and LightSwitch components. These are just props since the mapStateToProps function is handling all of that for us.

Now the trickier part is taking the onChange function from mapDispatchToProps and placing it in the LightSwitch so it can run the function. This bit of code: onChange={this.props.onChange} accomplishes that. Which the LightSwitch changes it passes the on/off value into the function we defined in the mapDispatchToProps which dispatches our action (with the value) to the store.

Hopefully this tutorial helped you understand how the basic setup of Redux works. To make a more complicated app will require much more advance concepts you can find elsewhere on the internet such as combined reducers, async thunks, more complicated states, etc.

A Monty Hall Probability Simulation

There are three doors. And hidden behind them are two goats and a car. Your objective is to win the car. Here’s what you do:

  • Pick a door.
  • The host opens one of the doors you didn’t pick that has a goat behind it.
  • Now there are just two doors to choose from.
  • Do you stay with your original choice or switch to the other door?
  • What’s the probability you get the car if you stay?
  • What’s the probability you get the car if you switch?

It’s not a 50/50 choice. I won’t digress into the math behind it, but instead let you play with the simulator below. The game will tally up how many times you win and lose based on your choice.

What’s going on here? Marilyn vos Savant wrote the solution to this game in 1990. You can read vos Savant’s explanations and some of the ignorant responses. But in short, because the door that’s opened is not opened randomly, the host gives you additional information about the set of doors you didn’t choose. Effectively, if you switch, you are select all the other doors. If you choose to stay, you are select just one door.

In her answer, she suggests:

Here’s a good way to visualize what happened. Suppose there are a million doors, and you pick door #1. Then the host, who knows what’s behind the doors and will always avoid the one with the prize, opens them all except door #777,777. You’d switch to that door pretty fast, wouldn’t you?

To illustrate that in the simulation, you can increase number of number of doors in the simulator. It becomes pretty clear that switch is the correct choice.

Finally, here’s some Kevin Spacey:

Make a HTML Table with jQuery

For a project I was working on, I needed a quick, simple solution to make a dynamic table based on data sent back from an AJAX call. I used jQuery to build and manipulate the table HTML, since it was quick to use jQuery and it’s already in my project.

After considering a few different ways to approach this, I decided different arrays would be the easiest way to handle the data. The data looks like this:

It’s a JavaScript object with two keys: one for the header that I abbreviated k and the main data values which have the key of v. The header is just an array of strings, while the values are an array of arrays. I specifically designed this code to work within these parameters, so there could be more checks built in, but the data source is rather rigid.

To make the Table class, I defined the attributes:

Using this prototype code is a little bit of overkill, but it can be reused and extended. I plan on having the application update with new data and possibly other features. Creating a prototype allows that to be a little bit easy and cleaner.

I have three setter methods, which just allow the Table object to have it’s attributes set and have the data set.

All the methods I’ve written have return this in them. That allows method chaining, which makes the implementation of the code a lot simpler. The meat of the code is in the build method.

I’ve annotated most of the code, but basically this creates jQuery objects for each of part of the table structure: the table (table), a row (tr), a header cell (th) and a normal table cell (td). The clone() method is necessary so that jQuery creates another HTML element. Otherwise it will keep on removing, modifying and appending the same element.

Using the prototype we just created is rather easy, we did the hard part already. We use the new keyword to instantiate a new object. This allows us to create many different independent Table objects which can be manipulated individually within the application.

Above is the short snippet of code which has method chaining. This allows us not to have to write separate lines of code for each method which would look like table.setData(). I used the setHeader() to set the array (data.k) which populates the table’s header. The setData() method sets the array of an array (data.v) as the source of the data for the rest of the table.

Finally, the build() method uses the data we just set to actually run the code that manipulates the HTML and this is what you see in your web browser.

Before using it on a web page, there has to be some HTML. (And some CSS so that the table looks decent.) The most important part is that the div container has the class of "table-container". The Table class is by default looking for that class to append the table to. You can customize that by changing using a jQuery selection string as a parameter in the table.build([jQuery selection string]) method.

Above is an working version of all the code from above. The full code I used for this post can be found on my GitHub .

D3 Visualization Basics — First Steps

D3 visualizations work by manipulating elements in the browser window. This short tutorial will demonstrate the very basics of that. This is also a working, simple demonstration of the interplay of HTML, CSS and JavaScript from the introduction page in this D3 tutorial set.

For the sake of making this simple, everything will come from one HTML document, which can be found in my GitHub . This will container the HTML and JavaScript. You can [and should] separate the JavaScript into its own file on bigger projects.

In this small project, we will start with a simple div container with the class of “container”.

Right now this doesn’t do anything, so it’s not worth showing. But if D3 code is added to create a blue box, it might look a little more interesting. [Provided you find blue boxes interesting.]

Blue Block

Above is a simple example of a basic D3 procedure. It can helpful to think about this command as having two parts: getting a DOM [browser] element to manipulate and giving instructions for those manipulations. Here is what the code is doing:

  1. The select statement [d3.selectAll()] code is finding every instance of the class of “container”. [There is only one element on the page.]
  2. The append() method adds another div as a child element inside of the container div.
  3. The attr() method gives the new div a class of “new-block”.
  4. The style() method gives the new div several style properties
  5. The text() method puts the text “Blue block” into the div

The style() and attr() methods can be a little confusing since they do similar things, but attr() will place attributes in the HTML tag, while style() writes in-line CSS for the element, which will override any CSS stylesheet you load in the header. These are just a few of the different methods you can use for a D3 DOM selection object, and you can find more in the D3 API reference.

Blue Block with Functions

Creating the blue block was a blast, but adding some functionality might make this a little more useful. Let’s make the block change color on a click and then remove it on a double click.

The first part of the script to create the blue block is the same, except I’ve doubled the code to have to blue blocks and I added new code that interacts with the blue block. The on() method allows you to attach an event listener to elements rendered in the browser. These will wait until a certain event happens. In the example it executes a function to turn the box orange when the blue box is clicked. You can put many different instructions in here and aren’t limited to manipulating the element that is being clicked. Below is an illustration that I find useful for visualizing how event listeners are attached. I will devote another post to the details of D3 event listeners.

attach event listeners

You might notice the d3.select(this) in the code. this is a fun keyword in JavaScript syntax which deals with scope, and the this in the code refers to the specific DOM element which was clicked or double clicked. If you click on the left block, only that block turns orange. You could change the code replace this with '.block-new' and clicking one button will change both buttons to orange.

Having the d3.select(this) code blocks in the event listener function makes it so they are only executed when the event happens. The block’s background color is changed to orange [#FF9821] when it’s clicked. The remove() method deletes any DOM elements within the selection including the children elements. This comes in handy when you need to rebuild or update a data visualization.

[Next]

Data! D3’s most powerful tool.

D3 Visualization Basics — Introduction

Data visualization is important, really important. I can’t be more blunt than that. We are able to process much more information faster by seeing a visual representation than we could look at a table, database or interacting with a spreadsheet. I will be writing a series of posts that explore some of the foundations D3 is built on along with how to create engaging data visualizations using it.

D3 is a powerful tool that allows you to create interactive data visualizations for the web. Understanding how D3 works starts with understanding how modern web pages are designed.

If you have found this page, you probably at least have some knowledge of how to make a modern website: HTML, CSS, JavaScript, responsive design, etc. D3 uses basic elements from these components of web design to create the visualizations. This by no means the only way to create interactive visualizations, but this is an effective way to produce them.

Before jumping into D3 nuts and bolts, let’s look at what does each of these components do. [If you already know this stuff, feel free to skip ahead…once I get the other posts built out.]

Basic Web Programming

In the most simplistic terms, HTML provides the structure of the webpage, CSS provides the styling and formatting, and JavaScript provides the functionality of the site. The browser brings these three components together and interprets them into something the end user (you) can understand and use. Sometimes one component can accomplish what the other does, but if you stick to this generalization you’ll be in good shape.

To produce a professional-looking, fully-functional D3 data visualization you will need to understand, write and manipulate all three components.

HTML

The most vivid memories I have of HTML is from the websites of the late 90s: Geocities, Angelfire, etc. HTML provides instructions on how browsers should interpret information; it organizes the information. Everything you see on a webpage has corresponding HTML code.

If you look at the source HTML or inspect one of this site’s page you’ll see some of the structure. When HTML renders in the browser these elements are referred to DOM elements. DOM stands for Document Object Model, which is the structure of a webpage.

HTML containers

Looking at the DOM tree you can see the many of the div containers that provide structure for the how the site is laid out. The p tags contain each paragraph in the content of my posts. h1, h2 and h3 are subheadings I’ve made to make the post more organized. You also notice some attributes especially class which have many uses for CSS, JavaScript and D3. Classes in particular are used to identify what function that DOM element plays in JavaScript or how to style it in CSS.

CSS

A house without painted walls or decorations is pretty boring. The same thing happens with bare bones HTML. You can organize the information, but it won’t be in an appealing format.

Most sites have style sheets (CSS) which sets margins, colors, display options, etc. Style sheets have a specific syntax which identifies HTML elements by type, class or id. This identification and selection concept is used extensively in D3.

CSS example

Above is some CSS from this site. It contains formatting instructions for elements of the class “page-links”. It includes instructions for the font size, margins, height, width and to make the text all uppercase. The advantage of CSS is that it keeps formatting away from the structure of the HTML allowing you to format many elements at once. For example if you wanted to change the color of every link, you could easily do that by modifying the CSS.

There is an alternative to using CSS style sheets and that’s by using inline style definitions.

Inline styles use the same markup as the CSS in the style sheets. Inline styles

  • control only the element they are in
  • OVERRIDE any CSS styles [without an !important tag]

The code above overrides the normal paragraph’s style property which aligns it left. Using inline styles are generally bad for web design, but it’s important to understand how they work since D3 manipulates inline styles often.

JavaScript

JavaScript breathes life into your web page. It certainly not the only way to have your website become interactive or build programming into it, but it is widely used and supported in the popular browsers. D3 is a JavaScript library, so you will inevitably have to write JavaScript to use it.

For D3 visualization, JavaScript will be use to

  • Manage and manipulate data for the visualization
  • Create DOM elements
  • Manipulate DOM elements
  • Destroy DOM elements
  • Attach data to DOM elements

JavaScript will be used insert elements onto the page, it will also be used to change colors and styles of those elements. You might be able to see how this could be useful. For example JavaScript could map data points to an element’s position for a scatter plot or to an element’s height or width for a bar chart.

I bolded the last function D3 does, attaching data to elements, because it’s so critical to D3. This allows you to attach a data point beyond x, y data to allow for rich visualization.

__data__

Above is data attached to a D3 visualization I made for FanGraphs. This is a simple example, but I was able to attach data detailing the team’s name, id, league, ERA and FIP. Using the attached data I was able to create the graph and tooltips. More complex designs can take advantage of the robust data structure D3 provides.

[Next]

I’ll look at how to set up a basic project by organizing data, files and code.