r/purescript • u/attilah • Jun 09 '18
How to call asynchronous functions from `createLifecycleComponent`'s eval function ?
I am using the library: https://github.com/doolse/purescript-reactnative
And I have been trying for hours to make a call to a JS function that returns a Promise from within an action evaluator.
My code looks like this:
1- Linking.js:
const RN = require('react-native'); exports.getInitialURLImpl = function(v) { return RN.Linking.getInitialURL(); } 2- Linking.purs:
foreign import data LINKING :: Effect foreign import getInitialURLImpl :: forall eff. Unit -> Eff eff (Promise String) getInitialURL :: forall eff. Aff (linking :: LINKING | eff) String getInitialURL = liftEff (getInitialURLImpl unit) >>= toAff 3- Main.purs:
initialState = {} data Action = HandleDeepLinking app :: forall p. ReactClass p app = createLifecycleComponent (didMount $ HandleDeepLinking) initialState render2 eval where eval (HandleDeepLinking) = void $ launchAff do x <- getInitialURL liftEff $ alert "test" (Just x) pure unit The above app
value does not typecheck. I don't know how to be able to access the result of a Promise from within the action evaluator.
Help!!!
1
Upvotes
View all comments
Show parent comment
1
u/attilah Jun 11 '18 edited Jun 11 '18
- I haven't used PureScript 0.12 so far. Also, purescript-reactnative hasn't been transitioned to 0.12 yet.- I've made use of purescript-aff and purescript-aff-promise, which I've liked really. I can easily transform JS functions that return Promise(s) into Aff.- I set the type to Eff eff (Promise String), but I use purescript-aff-promise to transform it into Aff eff (Maybe String)
1- Linking.js
exports.getInitialURLImpl = function(v) {
return function() {
return RN.Linking.getInitialURL();
}
}
exports.convertUndefinedOrNullToMaybe = function(value, just, nothing) {
if(!value) { return nothing; } else { return just(value); }
}
2- Linking.purs
type URL = String
foreign import data UndefinedOrNull :: Type -> Type
foreign import data LINKING :: Effect
foreign import openURL :: forall eff. URL -> Eff (linking :: LINKING | eff) Unit
foreign import getInitialURLImpl :: forall eff. Unit -> Eff eff (Promise (UndefinedOrNull String))
foreign import convertUndefinedOrNullToMaybe :: forall a. Fn3 (UndefinedOrNull a) (a -> Maybe a) (Maybe a) (Maybe a)
getInitialURL :: forall eff. Aff (linking :: LINKING | eff) (Maybe String)
getInitialURL = do
mUrl <- liftEff (getInitialURLImpl unit) >>= toAff
pure $ runFn3 convertUndefinedOrNullToMaybe mUrl Just Nothing