How to solve in ReasonReact - "This has type: (ReasonReact.reactElement, string) => unit But somewhere wanted: at <anonymous>actElement - reason

I have a very compact ReasonReact reducer component, which has a component, initialState, reducer, action, and render function as follows:
type actions =
| DoNothing;
let component = ReasonReact.reducerComponent("ShowHide");
let make = (~name, _children) => {
...component,
initialState: () => 0, /* here, state is an `int` */
reducer: (action, state) =>
switch action {
| DoNothing => ReasonReact.NoUpdate;
},
render: (self) => {
let greeting =
"Hello: " ++ name ++ ". You've clicked the button " ++ string_of_int(self.state) ++ " time(s)!";
<div></div>
}
};
I am trying to render in my app.re file using the ReactDOMRe.renderToElementWithId function:
<div id = "RenderShowHide"></div>
ReactDOMRe.renderToElementWithId(<ShowHide name="hello" />, "RenderShowHide")
However, the Reason/Bucklescript compiler is complaining as follows:
This has type:
(ReasonReact.reactElement, string) => unit
But somewhere wanted:
at <anonymous>actElement
However, I am having a difficulty what an actElement is. Any suggestions as to what an actElement is, and how I can go around fixing the above, would be more than appreciated. Thank you.

I tried the repo you posted: https://github.com/CharlieGreenman/reason-react-razroo
npm install
bsb -make-world
I got the following error message:
We've found a bug for you!
/Users/yawar/src/reason-react-razroo/src/app.re 16:9-40
14 ┆ </div>
15 ┆ <p className="App-intro">
16 ┆ ReactDOMRe.renderToElementWithId(<ShowHide name="hello"/>, "index")
17 ┆ (ReasonReact.stringToElement("To get started, edit"))
18 ┆ <code> (ReasonReact.stringToElement(" src/app.re ")) </code>
This has type:
(ReasonReact.reactElement, string) => unit
But somewhere wanted:
ReasonReact.reactElement
It looks like something in your build tooling was swallowing part of your error message. The main problem is on l. 16; if you get rid of that line the error will go away. If you want to render the ShowHide component, then change the line to just the literal JSX, not the call to ReactDOMRe.renderToElementWithId.
I have two more general recommendations; try to stick with the bsb-provided React skeleton project unless you are expert-level, because it's way simpler and much better supported:
bsb -init my-project -theme react
And, try to post the entire error message for future errors, starting from the 'We've found a bug for you!' line. That will help diagnose a lot.

Related

how to set babel plugins and presets - react-app-rewired

i am new to babel and testing stuff in react so it would be really great if you can provide a little more context for the approaches you can suggest.
Thank you
The app was created using react-app-rewired everything works fine but when i run my test script react-app-rewired test it throws this error
SyntaxError: C:\Users\kishan\Documents\GitHub\kp\client\src\components\DateTest\index.js: Support for the experimental syntax 'jsx' isn't currently enabled (219:5):
217 |
218 | return (
> 219 | <div className="date-test-container">
| ^
220 | <input
221 | ref={inputRef}
222 | type="text"
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Test file:
const React = require('react');
const {shallow} = require('enzyme')
const DateTest = require('./') // component needs to be tested
it('should render date test component and check current month',()=>{
// const wrapper = shallow(<DateTest />);
// const month = wrapper.find('span.monthName').text();
// expect(text).toEqual("March");
})
what i tried:
useBabelRc() from customize-cra can see the documentation here
Causes your .babelrc (or .babelrc.js) file to be used, this is especially useful if you'd rather override the CRA babel configuration and make sure it is consumed both by yarn start and yarn test (along with yarn build).
//inside my config-overrides.js
module.exports = override(
useBabelRc()
);
// inside my .babelrc
{
"presets": [ "#babel/preset-react"]
}
But getting the same error as above
please let me know if more information required

Intelllij doesn't support Play Framework very well?

I am using Intellij Idea + Scala Plugin + Play framework 2.6.0 to do web development.
I have a FruitController, its definition is:
def saveFruit = Action(BodyParsers.parse.json) { request =>
import FruitImplicits._
val fruitResult = request.body.validate[Fruit]
fruitResult.fold(
errors => {
BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))
},
fruit => {
println(s"Fruit is saved, the result is :$fruit")
Ok(Json.obj("status" -> "OK", "message" -> ("Fruit '" + fruit.name + "' saved.")))
}
)
}
The Intellij idea complains Missing parameter type:request for the request in the first line: Action(BodyParsers.parse.json) { request =>
But I could run the code successfully, so Intellij Idea has been mistakenly reported the error, I would ask how to get Intellij Idea to work well for this code
When I explicitly specify the type of the request: Request[JsValue], the problem is gone:
def saveFruit = Action(parse.json) { request: Request[JsValue] =>

Why this 'fail ->' caused invalid indentation error

This is my original code
new Data({ data_id: #model.get 'id' })
.fetch()
.done (result) =>
#_setUserInput(result.text)
.fail ->
bugsense.notify 'quickform results cannot be fetched' # error here
It caused the coffeescript compiler to throw this error message: Line contains inconsistent indentation (indentation)
Then I rewrite to
fail = -> bugsense.notify 'results cannot be fetched'
new Data({ data_id: #model.get 'id' })
.fetch()
.done (result) =>
#_setUserInput(result.text)
.fail fail
It passes
My first version looks correct. So what it caused the invalid indentation error?
You should have tabs and spaces mixed in your file, because I have tried to compile your code and It seems to be ok (you can check here that your code is right).
If your file uses 2 or 4 spaces to indent, and you are mixing spaces with tabs your compilation is going to fail because your file has unconsistent indentation.

how to componentize purescript-halogen application

I would like to write specific components of my frontend using Purescript's Halogen.
For example, I would like to create a registration form using Halogen. It would look something like below:
module RegistrationForm where
import Prelude
...
-- | The state of the application
newtype State = State { email :: String, password :: String }
derive instance genericState :: Generic State
instance showState :: Show State where show = gShow
instance eqState :: Eq State where eq = gEq
initialState :: State
initialState = State { email: "", password: "" }
-- | Inputs to the state machine
data Input a = FormSubmit a
| UpdateEmail String a
| UpdatePassword String a
| NoAction a
type AppEffects eff = HalogenEffects (ajax :: AJAX, console :: CONSOLE | eff)
ui :: forall eff . Component State Input (Aff (AppEffects eff))
ui = component render eval
where
render :: Render State Input
render (State state) = H.div_
[ H.h1_ [ H.text "Register" ]
, ...
]
eval :: Eval Input State Input (Aff (AppEffects eff))
eval (NoAction next) = pure next
eval (FormSubmit next) = do
...
eval (UpdateEmail email next) = do
...
eval (UpdatePassword password next) = do
...
runRegistrationForm :: Eff (AppEffects ()) Unit
runRegistrationForm = runAff throwException (const (pure unit)) $ do
{ node: node, driver: driver } <- runUI ui initialState
appendTo ".registration" node
Similarly, I have a LoginForm module that handles logging a user into the application.
I'm wondering how to go about organizing my source code, building my source code, and calling my Purescript code from Javascript?
Currently, my source code is organized like the following:
$ cd my-application/
$ tree
.
├── bower.json
├── README.md
├── site/
│ └── index.html
├── src/
│   ├── LoginForm.purs
│   └── RegistrationForm.purs
└── test/
   └── Test.purs
However, since I don't have a Main.purs, I can't do any of the following to build my source code:
$ pulp build --to site/app.js
$ pulp browserify --to site/app.js
$ pulp server
It would be nice to be able to build my purescript code into logical javascript files. For instance, src/LoginForm.purs could be built as site/loginForm.js, and src/RegistrationForm.purs could be built as site/registrationForm.js.
Then, I could include loginForm.js and registrationForm.js in my actual html pages as need-be.
Pulp doesn't really cover this use case, it's only intended for apps where there is a single Main.
I'd suggest using a gulp setup to achieve this, using a gulpfile something like this:
"use strict";
var gulp = require("gulp"),
purescript = require("gulp-purescript"),
webpack = require("webpack-stream");
var sources = [
"src/**/*.purs",
"bower_components/purescript-*/src/**/*.purs",
];
var foreigns = [
"src/**/*.js",
"bower_components/purescript-*/src/**/*.js"
];
gulp.task("make", function() {
return purescript.psc({
src: sources,
ffi: foreigns
});
});
var mkBundleTask = function (name, main) {
gulp.task("prebundle-" + name, ["make"], function() {
return purescript.pscBundle({
src: "output/**/*.js",
output: "tmp/js/" + name + ".js",
module: main,
main: main
});
});
gulp.task("bundle-" + name, ["prebundle-" + name], function () {
return gulp.src("tmp/js/" + name + ".js")
.pipe(webpack({
resolve: { modulesDirectories: ["node_modules"] },
output: { filename: name + ".js" }
}))
.pipe(gulp.dest("site/js"));
});
return "bundle-" + name;
};
gulp.task("bundle", [
mkBundleTask("loginForm", "LoginForm"),
mkBundleTask("registrationForm", "RegistrationForm")
]);
gulp.task("default", ["bundle"]);
That might not be quite right, but I extracted it from how we do things with SlamData so it's definitely along the right lines.
This is possible with pulp, using the --to and --main options:
pulp build --main LoginForm -O --to site/loginForm.js
pulp build --main RegistrationForm -O --to site/registrationForm.js
Of course, the LoginForm and RegistrationForm modules will both need to export a value called main for this to work.

Why makes calling error or done in a BodyParser's Iteratee the request hang in Play Framework 2.0?

I am trying to understand the reactive I/O concepts of Play 2.0 framework. In order to get a better understanding from the start I decided to skip the framework's helpers to construct iteratees of different kinds and to write a custom Iteratee from scratch to be used by a BodyParser to parse a request body.
Starting with the information available in Iteratees and ScalaBodyParser docs and two presentations about play reactive I/O this is what I came up with:
import play.api.mvc._
import play.api.mvc.Results._
import play.api.libs.iteratee.{Iteratee, Input}
import play.api.libs.concurrent.Promise
import play.api.libs.iteratee.Input.{El, EOF, Empty}
01 object Upload extends Controller {
02 def send = Action(BodyParser(rh => new SomeIteratee)) { request =>
03 Ok("Done")
04 }
05 }
06
07 case class SomeIteratee(state: Symbol = 'Cont, input: Input[Array[Byte]] = Empty, received: Int = 0) extends Iteratee[Array[Byte], Either[Result, Int]] {
08 println(state + " " + input + " " + received)
09
10 def fold[B](
11 done: (Either[Result, Int], Input[Array[Byte]]) => Promise[B],
12 cont: (Input[Array[Byte]] => Iteratee[Array[Byte], Either[Result, Int]]) => Promise[B],
13 error: (String, Input[Array[Byte]]) => Promise[B]
14 ): Promise[B] = state match {
15 case 'Done => { println("Done"); done(Right(received), Input.Empty) }
16 case 'Cont => cont(in => in match {
17 case in: El[Array[Byte]] => copy(input = in, received = received + in.e.length)
18 case Empty => copy(input = in)
19 case EOF => copy(state = 'Done, input = in)
20 case _ => copy(state = 'Error, input = in)
21 })
22 case _ => { println("Error"); error("Some error.", input) }
23 }
24 }
(Remark: All these things are new to me, so please forgive if something about this is total crap.)
The Iteratee is pretty dumb, it just reads all chunks, sums up the number of received bytes and prints out some messages. Everything works as expected when I call the controller action with some data - I can observe all chunks are received by the Iteratee and when all data is read it switches to state done and the request ends.
Now I started to play around with the code because I wanted to see the behaviour for these two cases:
Switching into state error before all input is read.
Switching into state done before all input is read and returning a Result instead of the Int.
My understanding of the documentation mentioned above is that both should be possible but actually I am not able to understand the observed behaviour. To test the first case I changed line 17 of the above code to:
17 case in: El[Array[Byte]] => copy(state = if(received + in.e.length > 10000) 'Error else 'Cont, input = in, received = received + in.e.length)
So I just added a condition to switch into the error state if more than 10000 bytes were received. The output I get is this:
'Cont Empty 0
'Cont El([B#38ecece6) 8192
'Error El([B#4ab50d3c) 16384
Error
Error
Error
Error
Error
Error
Error
Error
Error
Error
Error
Then the request hangs forever and never ends. My expectation from the above mentioned docs was that when I call the error function inside fold of an Iteratee the processing should be stopped. What is happening here is that the Iteratee's fold method is called several times after error has been called - well and then the request hangs.
When I switch into done state before reading all input the behaviour is quite similar. Changing line 15 to:
15 case 'Done => { println("Done with " + input); done(if (input == EOF) Right(received) else Left(BadRequest), Input.Empty) }
and line 17 to:
17 case in: El[Array[Byte]] => copy(state = if(received + in.e.length > 10000) 'Done else 'Cont, input = in, received = received + in.e.length)
produces the following output:
'Cont Empty 0
'Cont El([B#16ce00a8) 8192
'Done El([B#2e8d214a) 16384
Done with El([B#2e8d214a)
Done with El([B#2e8d214a)
Done with El([B#2e8d214a)
Done with El([B#2e8d214a)
and again the request hangs forever.
My main question is why the request is hanging in the above mentioned cases. If anybody could shed light on this I would greatly appreciate it!
Your understanding is perfectly right and I have just push a fix to master:
https://github.com/playframework/Play20/commit/ef70e641d9114ff8225332bf18b4dd995bd39bcc
Fixed both cases plus exceptions in the Iteratees.
Nice use of copy in case class for doing an Iteratee BTW.
Things must have changed with Play 2.1 - Promise is no longer parametric, and this example no longer compiles.