Tag Archives: Store

React, Redux, and Typescript – Why, What and How

This article covers adding Redux to an existing React application.

Redux is one of those technologies where you get introduced to it, and you think: this seems overly complex to solve such a simple problem. Quite often, this is, in fact, the case. I once read a post (which I cannot find) by Dan Abramov where he said a similar thing himself. Redux is a state manager, and if you’re using it for React, React does have facilities to manage its own state, so you may not need Redux.

In fact, from what I’ve seen, I’d say you’re better leaving it until you know you need Redux.


So, how will you know when you need Redux?

Well, you’ll know because you’ll raise some state, and suddenly realise that you’ve raised it into a component that has no business managing that state. My specific example was trying to manage user permissions.

Imagine the following menu structure:

		NavItem (React-Strap)
		LoginMenu.tsx (accesses the DB to get user info)

I needed to store a user permission, and conditionally display a menu option (NavItem); these are held in a LoginMenu component. This meant that my state would need to be in NavMenu.tsx – but that’s a strange place for the state regarding a user to live. Additionally, other parts of the application would need access to this, and so it’s time for a state manager.


Okay, we’ve talked about why you might want to add Redux. Let’s see, exactly what Redux is. Essentially, there are three concepts to Redux. Before I continue with my second rate explanation, I would strongly suggest you jump over to Dave Ceddia’s blog. If you’re trying to do this in Typescript, then come back afterwards – otherwise, stay there, there’s nothing I can tell you that he doesn’t cover in this article.


An action is simply an object that contains a property called type. It can contain other objects, too, and is used to send information from your application into the Redux Store.


Reducers are the engine of Redux. They accept an action, and the existing state of the application, and they return a new state.


The store holds the current application state. You cannot change this directly, but through an action.


(In this section, I’ll include some imports and file names – I’ll talk about project structure towards the end, and the imports and filenames will make sense then)

Let’s imagine that your application is a game, where you can move a character left and right; your application state might look like this:

export interface IStore = {
    position: 0

We’ll also need to create the store, which we can do in the same code file:


import { reducer } from '../State/Reducer';
import { createStore } from 'redux';

export interface IStore {
    position: number;

const store = createStore(reducer);
export default store;

Okay, so we have a state: we said that actions are the only things that can affect state (in fact we said through an action): let’s see what an action might look like:

export const MOVE = 'MOVE'

interface MoveAction {
    type: typeof MOVE

This would be sufficient, at least, this is all Redux needs; however, we need to know which way to move, etc. Convention seems to be to add a payload property; let’s see what that might look like:


export const MOVE = 'MOVE'
export interface Message {
    user: string
    message: string
    timestamp: number
interface MoveAction {
    type: typeof MOVE
    payload: Message
export type ActionTypes = MoveAction;

I’ve used a generic Message – you could make this specific to your action, but this sort of approach means that your messages are consistent across actions.

So, now we have a store (somewhere to keep the state), and an action something to indicate that we wish to update the state. However, looking at the action, it doesn’t seem to do too much updating… In fact, it’s just a message – it could even be just a string. We now need the final piece of the jig-saw: the reducer takes the action and updates the state; let’s see what that might look like:


import { InitialState } from './Store';
import { ActionTypes, MOVE } from './Actions';

export function reducer(state = InitialState, action: ActionTypes) {  
    console.log (action);
    switch (action.type) {
      case MOVE:
        return {
            position: state.position + parseInt(action.payload.message)
        return state;

There’s quite a lot here: (we’ll come back to InitialState shortly). Let’s go through a piece at a time.

The first thing we’re doing is checking the type parameter:

    switch (action.type) {
      case MOVE:

In a real world situation, there would be many options: you’re unlikely to have a single action, so the switch statement is necessary.

Remember earlier, we defined the action as MOVE:

export const MOVE = 'MOVE'

Which enables us to check for MOVE, rather than the magic string “MOVE”.

Inside the MOVE block, we’re accessing the payload:

      case MOVE:
        return {
            position: state.position + parseInt(action.payload.message)

The reducer must be a pure function: that is, it accepts and returns data, but it does not change anything; as a result, we’re returning a new version of the state that was passed in. We’re setting the new state to have a position which is based on the current position, but we’re not changing the state.

This code will crash if the message is set to “qwerty” (so if you’re doing this sort of thing yourself, you should do it better than I have!)

Finally, the default: block simply returns the same state that it was given; i.e. the state remains unchanged.

Initial State and Project Structure

I said we’d come back to initial state. In the reducer, we have the following:

export function reducer(state = InitialState, action: ActionTypes) {  

We have to define a starting state for the store; and you can do that like this:


export const InitialState: IStore = {
    position: 0

Before we move onto the application changes, let’s quickly talk about where this all goes. The frustrating answer is, it’s up to you; however, I found a structure like this quite useful, as it keeps all the Redux plumbing in a single place:

Plugging this into your app

So far, we’ve created a lot of code, but it’s been completely separate from your React application. Plugging it in is actually quite trivial. Let’s start with Index.tsx; you’ll need to import your reducer:

import { reducer } from './State/Reducer';

In the render function, you’ll then need to add the store into the DOM:

  <Provider store={store}>
    <BrowserRouter basename={baseUrl}>
      <App />

We can then access the store inside any component by simply referencing the Store.tsx:

import store from '../../State/Store';
import { MOVE } from '../../State/Actions';

And then calling the dispatch function:

                type: MOVE,
                payload: {
                    user: user.name,
                    message: "1",
                    timestamp: new Date().getTime()

We can also get the state by using this:


Connecting the State

This works okay, but there is an easier way; you can use the Redux Connect function. Essentially, instead of exporting the React class, you instead export a wrapper for it. Before that, though, you need to work out what you’re trying to map. You’ll need to split your props into three groups:

1. Props from the store that you want in your component
2. Props that you want to be passed into your component
3. Props from the store that are actually functions; that is, dispatch functions

You would then rewrite your component like this:

import { connect } from 'react-redux';
interface StoreProps {
   position: number;
interface OwnProps {
interface DispatchProps {

type Props = OwnProps & StoreProps & DispatchProps;
interface IState {
class GameComponent extends Component<Props, IState> {

Notice that you’re no longer exporting the GameComponent class. Instead, you add the following:

function mapStateToProps(state: IStore) {
  return {
    position: state.position
export default connect(mapStateToProps)(GameComponent);

This allows you to expose only the properties relevant to the component, but not the properties that you take from the Redux store.






Enabling Consumable Purchases in Windows Store Apps

What are consumables

Consumables are a type of in-app purchase that can be used within your app or game; by used, I mean, for example, coin, food, life-force, credit; anything that can be bought and then the same item be bought again. This is opposed to durables, which are in-app purchases, such as removing adverts, premium features, etc.

Where to go first

The MSDN article does cover most of what you need. However, it doesn’t seem to cover everything, hence this post.

The documentation for the CurrentAppSimulator is also useful.

The Principle

Actual purchasing is done through the CurrentApp class. However, there is an identical test version of this, which simulates the purchasing of in-app products. Part of the store certification process is to ensure you haven’t forgotten to switch these to their live counterparts; although using the #Debug and #Release configurations might be an idea, too (see the bottom of this post for more details on this).

Step 1 – WindowsStoreProxy.xml

When you run your application in real life, it will download the purchase information from the store. However, when you’re testing, you need to simulate this. The linked documents do have examples; however, IMHO, they don’t completely explain the implications of each section. Here’s an XML file:

<?xml version="1.0" encoding="utf-16" ?>
      <MarketData xml:lang="en-gb">
        <Name>App with several in-app products</Name>
        <Description>Sample app for demonstrating an expiring in-app product and a consumable in-app product</Description>
    <Product ProductId="MORE_CASH_1000" LicenseDuration="0" ProductType="Consumable">
      <MarketData xml:lang="en-gb">
        <Name>Consumable Item</Name>
    <Product ProductId="MORE_CASH_1000" TransactionId="00000001-0000-0000-0000-000000000000" Status="Active" />

It looks a lot like the MS example, with a few key differences: firstly, it only contains a single consumable; second, it’s in GBP; and thirdly, the “ConsumableInformation” is commented out. The single consumable is just because that’s what I’m working with, but the other two burnt me:

  • If you change the language or currency, you need to be consistent. I left an en-us in and it, point blank, refused to read the document. I spent a while checking the XML was the correct format, and finally just guessed at this.
  • The ConsumableInformation node is commented out. If you put it in, then when you read the license, it will tell you that it is unfulfilled. This is definitely useful for testing, but looks like a bug in your code if you don’t know this.

Store this in a Data folder within the project:


Step 2 – Create a helper class for managing the purchase

Obviously, this isn’t a requirement; but I would create a class for each consumable purchase. If you have common code then create a helper and base class as well.

namespace BetRaces.Purchases
    public class Purchase
        public const string MORE_CASH_PRODUCT = "MORE_CASH_1000";
        public const int MORE_CASH_AMOUNT = 1000;

The following steps are building on the existence of such a class.

Step 3 – Create a dictionary of purchased GUIDs

The idea here is that you can track what has been bought.

private Dictionary<string, List<Guid>> grantedConsumableTransactionIds;

Step 4 – Grant Feature Locally

If you read the linked documents, they suggest a version of this function; basically, you need a function that will perform the task that you’ve asked for. In this case, it will manage the purchase of the coins, time, bonus, whatever. The following code is pretty much an exact duplicate of that offered by MS:

        private async void GrantFeatureLocally(string productId, Guid transactionId)
            if (grantedConsumableTransactionIds == null)
                grantedConsumableTransactionIds = new Dictionary<string, List<Guid>>();

            if (!grantedConsumableTransactionIds.ContainsKey(productId))
                grantedConsumableTransactionIds.Add(productId, new List<Guid>());

            // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
            App.settings.CashPot.Total += MORE_CASH_AMOUNT;
            App.settings.SaveSettings();  // Ensure that the purchase is saved before reporting it as successful.
            FulfillmentResult result = await CurrentAppSimulator.ReportConsumableFulfillmentAsync(MORE_CASH_PRODUCT, transactionId);


Step 5 – Get Unfulfilled Consumables

The reasoning here is that you have started to make a purchase, but the line above `ReportConsumableFulfillmentAsync` has not been called. This then sits in a status which blocks future purchases.

        private async Task GetUnfulfilledConsumables()
            var products = await CurrentAppSimulator.GetUnfulfilledConsumablesAsync();

            foreach (UnfulfilledConsumable product in products)
                GrantFeatureLocally(product.ProductId, product.TransactionId);

Obviously, there is a risk that the code in step 4 will crash just at the point before you report the fulfilment; however, I’d rather that, than the user having paid for something they haven’t received.

Step 6 – Purchase

The next stage is a RequestProductPurchase() method; here’s the code:

        public async Task<bool> RequestProductPurchase(string productId)
            Uri uri = new Uri("ms-appx:///Data/WindowsStoreProxy.xml");
            Windows.Storage.StorageFile storeProxy = await StorageFile.GetFileFromApplicationUriAsync(uri);

            await CurrentAppSimulator.ReloadSimulatorAsync(storeProxy);
            Guid product1TempTransactionId;

            PurchaseResults purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
            if (purchaseResults == null) return false;

            switch (purchaseResults.Status)
                case ProductPurchaseStatus.Succeeded:
                    product1TempTransactionId = purchaseResults.TransactionId;

                    // Grant the user their purchase here, and then pass the product ID and transaction ID to currentAppSimulator.reportConsumableFulfillment
                    // To indicate local fulfillment to the Windows Store.
                    GrantFeatureLocally(productId, product1TempTransactionId);
                    return true;

                case ProductPurchaseStatus.NotFulfilled:
                    product1TempTransactionId = purchaseResults.TransactionId;

                    // First check for unfulfilled purchases and grant any unfulfilled purchases from an earlier transaction.
                    await GetUnfulfilledConsumables();

                    // Once products are fulfilled pass the product ID and transaction ID to currentAppSimulator.reportConsumableFulfillment
                    // To indicate local fulfillment to the Windows Store.
                    if (grantedConsumableTransactionIds != null && grantedConsumableTransactionIds.ContainsKey(productId))
                        return true;
                    return false;                    

            return false;

The above code is what I was referring to in Step 1, when I mentioned the NotFulfilled return status.

Step 7 – Test the change

When you try to make a purchase, you should see a screen such as this:


You can then test possible eventualities.

Step 8 – Enable them in the store

The next step is to enable your purchases in the App Store. The code has to be the same; and for larger games (the producers of which will probably not be reading posts such as this) the codes will be generated on a server, so they can manage special offers, etc. centrally.

In the Services section of the dashboard:


Now enter your offer code, along with the price and make it a “Consumable”:


Step 9 – The Old Switcheroo

All you need to do now is to substitute CurrentAppSimulator for CurrentApp.

Because both classes are static, I couldn’t find a better way than this:

            PurchaseResults purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
            PurchaseResults purchaseResults = await CurrentApp.RequestProductPurchaseAsync(productId);

Windows Store Apps automatically compile in Release mode for the store.

Once you’ve found all the CurrentAppSimulator references and replaced them with this conditional construct (by my count there are 4 places for this); you should see the following when you try to make the purchase:




The links at the start are by far the best resource available for this; but hopefully this will fill in a couple of the gaps that tripped me up.