如何使用Pux处理效果?

时间:2017-06-10 18:22:24

标签: purescript purescript-pux

我只是Purescript和Pux整个世界的初学者,所以我对处理效果的地方感到有些困惑。

目前我正在为我的类型中的效果建模:

type State = { countries ∷ Maybe (Eff (random :: RANDOM) Countries) }

然后在我的foldp函数中使用它:

foldp (Request) state = { state, effects: [countries] }

countries定义为:

countries = do
  response <- attempt $ get "/countries.json"
  let countries = either (Left <<< show) decode response
  pure $ Just $ Receive $ case shuffle <$> countries of
    Left _   → Nothing
    Right xs → Just xs

但是在某些时候我需要从类型中解开 RANDOM效果,以便能够从我的视图中返回它:State → HTML Event

1 个答案:

答案 0 :(得分:1)

您根本不在视图中执行任何副作用。解除折叠中的随机效果:

data Countries
data Event = Request | Received (Maybe Countries) | FetchError String

type State =  {countries :: Maybe Countries, error :: String}

type AppFx fx = (random :: RANDOM | fx)

foldp :: ∀ fx. FoldP State Event (AppFx fx)
foldp (FetchError msg) state = noEffects state{error = msg}
foldp (Received countries) state = noEffects state{countries = countries}
foldp Request state = {state, effects: pure countriesRequest}
  where
  countriesRequest = Just <$> do
    response <- attempt $ getCountries
    case response of
      Left errorMsg -> pure $ FetchError $ show errorMsg
      Right countries -> case shuffle countries of
          Left _ -> pure $ Received Nothing
          Right shuffleEff -> do
            shuffledCountries <- liftEff shuffleEff
            pure $ Received $ Just shuffledCountries

shuffle :: ∀ fx. Countries -> Either String (Eff (random :: RANDOM | fx) Countries)
shuffle = unsafeCrashWith "TODO"

getCountries :: ∀ fx. Aff fx Countries
getCountries = unsafeCrashWith "TODO"