Skip to content

Commit 809ad59

Browse files
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.
1 parent 1b37ba0 commit 809ad59

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/React.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ function readState(this_) {
5353
}
5454
exports.readState = readState;
5555

56+
function transformState(this_){
57+
return function(update){
58+
return function(){
59+
this_.setState(function(old, props){
60+
return {state: update(old.state)};
61+
});
62+
};
63+
};
64+
}
65+
exports.transformState = transformState;
66+
5667
function createClass(spec) {
5768
var result = {
5869
displayName: spec.displayName,

src/React.purs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -284,10 +284,7 @@ foreign import writeState :: forall props state access eff. ReactThis props stat
284284
foreign import readState :: forall props state access eff. ReactThis props state -> Eff (state :: ReactState (read :: Read | access) | eff) state
285285

286286
-- | Transform the component state by applying a function.
287-
transformState :: forall props state eff. ReactThis props state -> (state -> state) -> Eff (state :: ReactState ReadWrite | eff) state
288-
transformState ctx f = do
289-
state <- readState ctx
290-
writeState ctx $ f state
287+
foreign import transformState :: forall props state eff. ReactThis props state -> (state -> state) -> Eff (state :: ReactState ReadWrite | eff) Unit
291288

292289
-- | Create a React class from a specification.
293290
foreign import createClass :: forall props state eff. ReactSpec props state eff -> ReactClass props

0 commit comments

Comments
 (0)