I try to use react-rails
with jbuilder.
For example, I use this great sample app of react-rails and try to rewrite to use jbuilder as a json response using reference from this part in react-rails
.
These are the main rewrite parts:
# app/views/comments/index.html.erb
<%= react_component 'CommentBox', render(template: 'comments/index.json.jbuilder'), {prerender: true} %>
# app/views/comments/index.json.jbuilder
json.presenter do
json.comments(@comments) do |comment|
json.extract! comment, :id, :author
end
json.form do
json.action comments_path
json.csrf_param request_forgery_protection_token
json.csrf_token form_authenticity_token
end
end
json.imgSrc image_path("gundam.jpg")
But I got an following error:
Started GET "/comments" for 127.0.0.1 at 2015-04-07 18:26:40 +0900
Processing by CommentsController#index as HTML
Comment Load (0.9ms) SELECT "comments".* FROM "comments" ORDER BY "comments"."id" DESC LIMIT 5
Rendered comments/index.json.jbuilder (8.4ms)
Rendered comments/index.html.erb within layouts/application (34.6ms)
Completed 500 Internal Server Error in 43ms
ActionView::Template::Error (SyntaxError: Unexpected token o):
app/views/comments/index.html.erb:3:in `_app_views_comments_index_html_erb___3472795088323540071_70123597415980'
Do you have any idea to solve this error? Thanks in advance.
see full source code: Use jbuilder but it gets an error · jwako/sample-react-rails-app@508d581
It looks like the unexpected token is raised because the CommentBox component is calling JSON.parse()
in getInitialState
when this.props.presenter
is already a JSON object.
You can fix it by removing JSON.parse()
in getInitialState
and returning only this.props.presenter
.
Here is a related answer on parsing existing JSON objects.