Updating my React Sudoku Solver app: Replacing Flux with Redux (part 2)

In the first part of converting my Sudoku solver React app from using Flux to Redux I looked at creating the Redux Store, Action Creators, reducers, and connecting Components to the Store. In this part 2 I’m taking a look at using redux-thunk for making my api calls.

Async API calls are integrated into a Redux app by using a ‘thunk’, support is provided by adding react-thunk to your app:

npm install --save redux-thunk

react-thunk is a middleware for your Redux Store. It looks at each Action dispatched to your Store and if it’s a function instead of an Action object it executes it.

Where you create your store with createStore(), add an import for applyMiddleware and thunk:

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const middlewares = [thunk];

Pass a call to applyMiddleware as a param to createStore() passing this middlewares array. In my app I’ve already passed the devToolsEnhancer() to createStore():

let store = createStore(puzzleDataReducer, devToolsEnhancer());

Naively, I thought I’d be able to add thunk and devToolsEnhancer() in the array and pass like this:

const middlewares = [thunk, devToolsMiddleware()];
let store = createStore(puzzleDataReducer, applyMiddleware(...middlewares));

… but this leads to some rather cryptic errors and I’ve honestly no idea what this means or how to resolve it:

VM1047:1 Uncaught TypeError: t.apply is not a function
     at :1:47480
     at :1:33759
     at :1:26192
     at eval (redux.js:602)
     at eval (redux.js:646)
     at createStore (redux.js:79)

Luckily a quick search found this article, suggesting the way to combine these enhancers is to use redux’s compose() function. Import compose from redux:

import { createStore, applyMiddleware, compose } from 'redux';

Use compose() to combine thunk and the devToolsEnhancer() call like this:

compose(
   applyMiddleware(thunk, otherMiddleware()),
   window.devToolsExtension ? window.devToolsExtension() : f => f
 )

In my case I don’t have other middleware to include, so my createStore() was originally this:

let store = createStore(puzzleDataReducer, devToolsEnhancer());

and now including thunk and using compose() it looks like this:

let store = createStore(puzzleDataReducer, compose(
    applyMiddleware(thunk),
    window.devToolsExtension ? window.devToolsExtension() : f => f
    )
);

Next I need to move my Flux Action that makes my api call to a function that is returned by an Action Creator. Since react-thunk looks for functions returned by Action Creators instead of Action objects and executes them. this was a relatively minor change moving the function from my original Action to my Action Creator.

At this point I’ve got a working app, migrated from Flux to Redux. You can check the final result on GitHub here. I’ve still got some cleanup to do – in particular I don’t have a clean separation between my reducer code and my Action Creator code. I’ll code back and do some cleanup later, and also deploy a parallel copy of the same app to AWS. Right now the original Flux based app is deployed here. I’ll deploy the final Redux based app shortly.

Updating my React Sudoku Solver app: Replacing Flux with Redux (part 1)

A while back I built a React frontend for a AWS Lambda Sudoku solver. At the time I used Flux (original source for this app is here), but I’m taking a look at updating it to replace Flux with Redux.

As a starting point I took another example React app, a simplest case app using Flux and then converted it to Redux. After working through the changes to update this app to use Redux, I put together a quick cheatsheet of changes here. Here’s both projects for a comparison:

https://github.com/kevinhooke/SimpleReactFluxExample

https://github.com/kevinhooke/SimpleReactReduxExample

Here’s a walkthrough of the main changes to an existing app (summarizing the steps from my cheatsheet, link above, and looking at some of the steps in more detail):

  • install react-redux and react-devtools-extension
  • create a store using Redux createStore, replacing previous Flux store that used Dispatcher, EmitEvent and [add|remove]ChangeListeners
  • create reducers to manipulate the Store
  • wrap root component with <Provider>
  • connect components with the Store

The Redux approach to maintaining state in the Store is significantly different from Flux:

  • Redux has a single store, whereas Flux can have many
  • State maintained in a Redux Store is manipulated with reducer functions
  • Reducer functions take the state to be manipulated and actions that are applied to the state to change it
  • Flux maintains a copy of the state in variables in the Store itself, whereas the current state of the store is passed as an argument to reducers, and a new updated copy is returned as the result

Since there’s a number of changes to the store, it’s worth looking at each of these in more detail.

Updating Flux Store to a Redux Store

Previously my Flux store maintained state in two vars:

var puzzleData = {}
var message = {}

These are no longer needed in the Redux store, but there in an initialState for initializing the Store. This can simply be the same as puzzleData before but just renamed for clarity:

const initialPuzzleData = {}

Next, each of the case statements in the Action can move over to the reducer function, and updated to manipulate the content of the store passed as a param and then return the modified store as the result. For example, previously each action was handled like this:

case 'NEW_DATA' :
  this.setData(action.data);
  this.emit('change');
  break;

With Redux, each case block is now going to look more like this:

case 'NEW_DATA' :
  return Object.assign( {}, action.data );

Create ActionCreators

In Flux, an Action combines a couple of concepts, it’s the payload to be dispatched to the Store as well as the mechanism for performing the dispatch of the Action. With Redux these concepts are separate, and the Action is merely the payload to apply to updating the Store. There is a concept of Action Creators though, that can be called to build the Action payload. Before with Flux we would have an Action function like this:

    initSamplePuzzle(){
        console.log("SudokuSolverAction initSamplePuzzle()");
        var puzzle = {
            rows:
                [
                    ["", "", "", "8", "1", "", "6", "7", ""],
                    ["", "", "7", "4", "9", "", "2", "", "8"],
                    ["", "6", "", "", "5", "", "1", "", "4"],
                    ["1", "", "", "", "", "3", "9", "", ""],
                    ["4", "", "", "", "8", "", "", "", "7"],
                    ["", "", "6", "9", "", "", "", "", "3"],
                    ["9", "", "2", "", "3", "", "", "6", ""],
                    ["6", "", "1", "", "7", "4", "3", "", ""],
                    ["", "3", "4", "", "6", "9", "", "", ""]
                ]
        }

        AppDispatcher.dispatch({
            actionName: 'NEW_DATA',
            data: puzzle.rows
        });
    }

and now this is simplified to build the payload, the Flux Dispatcher is removed, and the function. now just returns the payload to be processed:

    return {
        actionName: 'NEW_DATA',
        data: puzzle.rows
    };

Another simple example that builds an Action object for an update to the Store:

export function updateGrid(payload) {
    return { type: NEW_DATA, payload }
};

Connecting Components to the Store

In each Component, implement mapStateToProps and mapDispatchToProps to pass store and dispatch() as props to each Component, and call connect() to connect each Component with your Redux Store.

Here’s my matchStateToProps:

const mapStateToProps = state => {
    return { 
        grid: state.grid,
        message: state.message
     };
};

And here’s my mapDispatchToProps:

function mapDispatchToProps(dispatch) {
    return {
        updatePuzzleData :  grid => dispatch(updatePuzzleData(grid)),
        clearData : () => dispatch(clearData()),
        initSamplePuzzle : () => dispatch(initSamplePuzzle())
    }
}

mapDispatchToProps is where your Action Creators are called to create Action objects for modifying state, and then dispatched to apply against the state of the Store by your reducers.

Connect your components to your Store with a call to connect() :

const SudokuSolver = connect(mapStateToProps, mapDispatchToProps)(ConnectedSudokuSolver);

export default SudokuSolver;

Part 2

In part 2 I’ll look at moving the api call from the Flux Action to use Redux middleware and thunks.

React Redux cheatsheet

This is my summary of the bare minimum steps as a quick-ref cheatsheet for adding Redux to an existing React app. This is just some notes for future reference. If you’re looking for tutorials, take a look at:

Here’s my quickref:

npm install --save react-redux

Add Redux devtools for Chrome (see here):

npm install --save-dev redux-devtools-extension

Wrap <Provider> around root Component to share the Store with all child components:

import { Provider } from 'react-redux'
import store from './store'

<Provider store={store}>
  <App>
</Provider>

Implement mapStateToProps and mapDispatchToProps to pass store and dispatch() as props to each Component, and call connect() to connect each Component with your Redux Store:

const mapStateToProps = (state) => {
  return {
    yourcomponent: state.yourcomponent
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(YourComponent)

Create a Store:

import { createStore } from 'redux';
import { devToolsEnhancer } from 'redux-devtools-extension';
let store = createStore(yourReducer, devToolsEnhancer());
export default store;

Create reducers for Store – here’s an example that take the the value of a label from the passed action payload and sets it in the Store – remember the state of the store is always treated as immutable, so always create a new copy of the modified state, here using Object.assign():

function labelReducer(state = initialState, action) {
  switch (action.type) {
    case 'CHANGE_LABEL':
      return Object.assign( {},{ labelValue : action.payload 
    } );
    default:
      return state;
    }
}

Implement an action creator that builds an Action object that requests changes to the Store – each action has a type and a payload:

export function changeLabel(payload) {
  return { type: "LABLE_CHANGE", payload }
};

Implement mapDispatchToProps – you can either build the Action object yourself here, or call an Action creator like the above example:

function mapDispatchToProps(dispatch) {
return {
  changeLabel: labelValue => 
    dispatch(changeLabel(labelValue))
  };
}

Pass mapDispatchToProps to your connect() call shown earlier.

As a comparison, here’s a simple React app using Flux:

https://github.com/kevinhooke/SimpleReactFluxExample

… and here’s the same app converted to use Redux:

https://github.com/kevinhooke/SimpleReactReduxExample

Done!

Building a React frontend for my AWS Lambda Sudoku solver

Over the past few months I built an implementation of Donald Knuth’s Algorithm X using Dancing Links in Java to solve Sudoku puzzles.

This was a fascinating exercise in itself (you can read more my experience here), but the next logical step would be to package it up in a way to share it online.

Since I’m pursuing my AWS certifications right now, one interesting and low cost approach to host the the Solver implementation is to package it as an AWS Lambda. Sudoku Solver as a Service? Done. I exposed it through AWS API Gateway. It accepts an request payload that looks like this:

{"rows":["...81.67.","..749.2.8",".6..5.1.4","1....39..","4...8...7","..69....3","9.2.3..6.","6.1.743..",".34.69..."]}

and returns a response with a solution to the submitted puzzle request like this:

{"rows":["349812675","517496238","268357194","185723946","493681527","726945813","972538461","651274389","834169752"]}

The request and response payloads are an array of Strings, where each item represents a String of values concatenated together for one row in the grid, with ‘.’s for unknowns.

I’m still learning React as I go, and while building this front end for my Lambda Sudoku Solver I learnt some interesting things about React and Javascript. The source for the app is shared here.

I used Flux to structure the app, so there main parts of the app are:

  • a main, highlevel Container component,
  • a CellComponent that renders each cell in the Sudoku grid,
  • an Action that handles the interaction with the AWS Lambda
  • a Store that holds the results from calling the Lambda

I don’t want to focus on the pros and cons of using React or Flux (and this is not intended to be a how-to on building an app using React) as there were some other specific issues I ran into that were interesting learning opportunities. A couple of these I already captured in separate posts, so I’ll include these links below.

Iteration 1: onChange handler per row

My first approach to maintaining the state for the display of the grid and the handler for changes to each cell was to keep it simple and have a seperate array of values per row, and a separate onChange handler for each row. This is not a particularly effective way to structure this as there’s duplication in each of the 9 handlers.

The State looked like this:

this.state =
{
row1 : [],
row2 : [],
row3 : [],
row4 : [],
row5 : [],
row6 : [],
row7 : [],
row8 : [],
row9 : []
};

And each of the handlers looked like this, one handler per row, so handleChangeRow1() through handleChangeRow9():

handleChangeRow1(index, event){
console.log("row 1 update: " + event.target.value);
var updatedRow = [...this.state.row1];
updatedRow[index] = event.target.value
this.setState( { row1 : updatedRow } );
}

This approach needed 9 versions of the function above, each one specifically handling updates to the state for a single row. We’ll come back to improving this later.

The interesting thing to notice at this point that to update an array in React state, you need to clone a copy of the array, and then update the copy. I used the spread operator ‘…’ to clone the array.

Each row in the grid I rendered separately like this (so this approach needed 9 of these blocks):

<div>
{
this.state.row1.map( (cell, index) => (
<CellComponent key={index} value={this.state.row1[index]}
onChange={this.handleChangeRow1.bind(this, index)}/>
)
)}
</div>

This was my first working version of the app, at least at the point where I could track the State of the grid as a user entered or changed values in the 9×9 grid. Next steps was to improve the approach.

Iteration 2: Using an array of arrays for the State

The first improvement was to improve the State arrays, moving to an array of arrays. This is easily setup like this:

this.state =
{
grid: []
};

for (var row = 0; row < 9; row++) {
this.state.grid[row] = [];
}

Iteration 3: One onChange handler for all rows

Instead of a handler per row, I parameterized the onChange handler to reused for all rows. This is what I ended up with:

handleGridChange(row, colIndex, event) {
console.log("row [" + row + "] col [" + colIndex + "] : " + event.target.value);
var updatedGrid = [...this.state.grid];
updatedGrid[row][colIndex] = event.target.value;

//call Action to send updated data to Store
SudokuSolverAction.updatePuzzleData(updatedGrid);
}

Using .map() on each of the rows in State, I then rendered each row of the grid like this, passing the current row index and column index as params into handleGridChange():

<tr>
{
this.state.grid[0].map((cell, colIndex) => (
<td key={"row0" + colIndex}>
<CellComponent value={this.state.grid[0][colIndex]}
onChange={this.handleGridChange.bind(this, 0, colIndex)}/>
</td>
)
)}
</tr>

I’m sure there’s a way to use a nested .map() of the results of a .map() or some other clever approach to render the whole grid in a single go, but rendering each of rows individual is an ok approach with me since there’s only 9 rows. If the number of rows were much more than 9 then I’d spend some time working on a better approach, but I’m ok with this for now.

Flux Action and Store

The Action to call the Lambda, and maintaining the state of the responses in the Store was pretty simple. You can check out the source here if you’re interested.

CSS styling for the grid

One last thing to do was to style the grid so it looks like a usual Sudoku grid, with vertical and horizontal lines at 3 and 6, to divide the grid in 3×3 of the 3×3 squares. This took some reading to find out how to easily do this, but turns out CSS nth-child() psuedoclass handles this perfectly. I covered this in this post here.

Take a look at the app

I might move this to a more permanent home later, but if you want to check out the app, you can take a look here.