I'm working on a project that uses Flask as a backend and sends data from MongoDB database and sends it to React to print on the screen. In the Flash file
@app.route('/') @app.route('/post') def post(): db = connection.posthub cursor = db.post.find() //make the cursor return render_template('index.html', cursor = cursor) //render template index.html with cursor
In the pug file.
extends main block content | {% for post in cursor %} //Interating cursor with post variable #demo {{ post }} // sending post to demo for react to render |{% endfor %}
In React file
import React from 'react'; import ReactDOM from 'react-dom'; class NewComponent extends React.Component { constructor(props){ super(props); this.state = {myData:{}} } componentDidMount(){ console.log("Mounting Components") let data = document.getElementById('demo').InnerHTML; //getting data from html tag console.log(typeof(data)); data = JSON.parse(data); // parse it this.setState({myData:data}); //set the state } render(){ return( <h3>{this.state.myData}</h3> //print it ); } } ReactDOM.render( <NewComponent />, document.getElementById('demo') )
It's printing:
{u'_id': ObjectId('597619b7c07b2dc30a108def'), u'description': u'hello', u'title': u'sankit'} {u'_id': ObjectId('59761b2cc6568a4e341b6b89'), u'description': u'lets add some thing new', u'title': u'hi'}
In the console giving the error:
bundle.js:830 Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `NewComponent`.
and I was not able to print only the value of a specific key. need help
Edits: As suggested by @im_benton and @TW80000 I have some changes.
First I used bson_json_util.dumps while sending the cursor so that i'm sending a string not a list.
return render_template('index.html', cursor = dumps(cursor))
Then in the pug file, I used window to create global variable and send the cursor to React
block content #demo script | window.data = {{ cursor }};
Then in the React file, I tried to parse the string to JSON and render it iterating through it.
componentWillMount(){ console.log("Mounting Components"); let data = window.data; console.log(data); data = JSON.parse(data); console.log(data); this.setState({myData: data}); } render() { return this.state.myData.map(item => { return ( <div> <h3>{item.title}</h3> <p>{item.description}</p> </div> ); }) }
Still, i'm getting an empty array in console.log and if I don't use dumps an undefined object.
Mounting Components bundle.js:20844 Array(0) localhost/:1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at NewComponent.componentWillMount (bundle.js:20845) at bundle.js:6685 at measureLifeCyclePerf (bundle.js:6412) at ReactCompositeComponentWrapper.performInitialMount (
Can you Help?