From 809ad59de91f0180fc9ed5a3e8c0a9c76eaa9fb5 Mon Sep 17 00:00:00 2001 From: Spencer Janssen Date: Thu, 25 Feb 2016 17:04:43 -0800 Subject: [PATCH] Fix transformState to use current state According to React's docs: setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. To make sure that transformState gets the latest value, we use setState's callback mode. transformState now returns Unit instead of the state type. --- src/React.js | 11 +++++++++++ src/React.purs | 5 +---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/React.js b/src/React.js index 2d42dd1..6833ab4 100644 --- a/src/React.js +++ b/src/React.js @@ -53,6 +53,17 @@ function readState(this_) { } exports.readState = readState; +function transformState(this_){ + return function(update){ + return function(){ + this_.setState(function(old, props){ + return {state: update(old.state)}; + }); + }; + }; +} +exports.transformState = transformState; + function createClass(spec) { var result = { displayName: spec.displayName, diff --git a/src/React.purs b/src/React.purs index a5c63fb..15541ab 100644 --- a/src/React.purs +++ b/src/React.purs @@ -284,10 +284,7 @@ foreign import writeState :: forall props state access eff. ReactThis props stat foreign import readState :: forall props state access eff. ReactThis props state -> Eff (state :: ReactState (read :: Read | access) | eff) state -- | Transform the component state by applying a function. -transformState :: forall props state eff. ReactThis props state -> (state -> state) -> Eff (state :: ReactState ReadWrite | eff) state -transformState ctx f = do - state <- readState ctx - writeState ctx $ f state +foreign import transformState :: forall props state eff. ReactThis props state -> (state -> state) -> Eff (state :: ReactState ReadWrite | eff) Unit -- | Create a React class from a specification. foreign import createClass :: forall props state eff. ReactSpec props state eff -> ReactClass props