I've recently updated to meteor 1.3 and I'm having trouble with the createContainer function. The app is supposed re-render when the props change, however, it's not happening. I'm working with the example from this page but nothing is happening, the app only displays the header. No errors are present.
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Tasks } from '../api/tasks.js';
import Task from './Task.jsx';
class App extends Component {
renderTasks() {
return this.props.tasks.map((task) => (
<Task key={task._id} task={task} />
));
}
render() {
return (
<div className="container">
<header>
<h1>Header</h1>
</header>
<ul>
{this.renderTasks()}
</ul>
</div>
);
}
}
App.propTypes = {
tasks: PropTypes.array.isRequired,
};
export default createContainer(() => {
return {
tasks: Tasks.find({}).fetch(),
};
}, App);
tasks.js:
import { Mongo } from 'meteor/mongo';
export const Tasks = new Mongo.Collection('tasks');
I've been stuck for longer for more than I'm willing to admit, what am I missing?
Your renderTasks method has no idea what this is, since React classes do not do auto-binding. Modify your component to be this instead:
class App extends Component {
renderTasks() {
return this.props.tasks.map((task) => (
<Task key={task._id} task={task} />
));
}
render() {
return (
<div className="container">
<header>
<h1>Header</h1>
</header>
<ul>
{this.renderTasks.call(this)}
</ul>
</div>
);
}
}
Or alternatively, you could do meteor npm install --save react-autobind and insert this constructor which will automatically bind everything for you:
import autoBind from 'react-autobind';
class App extends Component {
constructor(props) {
super(props);
autoBind(this);
}
// ...
}
It had nothing to do with the code and everything to do with me accidentally placing my server code inside the client code while migrating to Meteor 1.3
I'm not sure why this didn't cause any errors though.
It's missing the reference of React:
App.propTypes = {
tasks: PropTypes.array.isRequired,
};
to
App.propTypes = {
tasks: React.PropTypes.array.isRequired,
};
Related
I'm trying to use CodeMirror on Vue3 and the problem occurs when I call doc.setValue().
The Problem is following:
Cursor position is broken when doc.setValue() is called
CodeMirror throws an exception when continuing editing
The exception is here.
Uncaught TypeError: Cannot read property 'height' of undefined
at lineLength (codemirror.js:1653)
at codemirror.js:5459
at LeafChunk.iterN (codemirror.js:5623)
at Doc.iterN (codemirror.js:5725)
at Doc.iter (codemirror.js:6111)
at makeChangeSingleDocInEditor (codemirror.js:5458)
at makeChangeSingleDoc (codemirror.js:5428)
at makeChangeInner (codemirror.js:5297)
at makeChange (codemirror.js:5288)
at replaceRange (codemirror.js:5502)
How should I solve this?
~~~
Versions are CodeMirror: 5.61.1, Vue.js: 3.0.11
My code is following:
index.html
<div id="app"></div>
<script src="./index.js"></script>
index.js
import { createApp } from 'vue';
import App from './App';
const app = createApp(App);
app.mount('#app');
App.vue
<template>
<div>
<button #click="click">Push Me</button>
<textarea id="codemirror"></textarea>
</div>
</template>
<script>
import CodeMirror from 'codemirror/lib/codemirror.js';
import 'codemirror/lib/codemirror.css';
// import codemirror resources
import 'codemirror/addon/mode/overlay.js';
import 'codemirror/mode/markdown/markdown.js';
import 'codemirror/mode/gfm/gfm.js';
export default {
data () {
return {
cm: null
}
},
mounted () {
this.cm = CodeMirror.fromTextArea(document.getElementById('codemirror'), {
mode: 'gfm',
lineNumbers: true,
});
},
methods: {
click (event) {
this.cm.getDoc().setValue('foo\nbar');
}
}
}
</script>
Thanks.
UPDATES
First, this problem also occurs when I used replaceRange() with multiline.
Unfortunately, I couldn't find any solution. So I tried to find another way.
My solution is recreating Codemirror instance with a textarea that has new content.
It works well.
// Remove old editor
this.cm.toTextArea();
// Get textarea
const textarea = document.getElementById('codemirror');
// Set new content
textarea.value = 'foo\nbar';
// Create new editor
this.cm = CodeMirror.fromTextArea(textarea, { /** options */ });
I found a method, you can use toRaw to get the original Object from Proxy,and this method can be also used in monaco-editor
import { toRaw } from 'vue'
import CodeMirror from 'codemirror/lib/codemirror.js';
import 'codemirror/lib/codemirror.css';
// import codemirror resources
import 'codemirror/addon/mode/overlay.js';
import 'codemirror/mode/markdown/markdown.js';
import 'codemirror/mode/gfm/gfm.js';
export default {
data () {
return {
cm: null
}
},
mounted () {
this.cm = CodeMirror.fromTextArea(document.getElementById('codemirror'), {
mode: 'gfm',
lineNumbers: true,
});
},
methods: {
click (event) {
toRaw(this.cm).setValue('foo\nbar');
}
}
}
Another way,you don't have to define cm in data, just use this.cm
data () {
return {
//cm: null
}
},
I am trying to understand how decorators work with Meteor 1.4. From what I read, this feature is supported.
Now, I am unsure how to actually implement it. From this blog, to decorate a class, I would require this code
export const TestDecorator = (target) => {
let _componentWillMount = target.componentWillMount;
target.componentWillMount = function () {
console.log("*** COMPONENT WILL MOUNT");
_componentWillMount.call(this, ...arguments);
}
return target;
}
Then use it as
import React, { Component } from 'react';
import { TestDecorator } from 'path/to/decorator.js';
#TestDecorator
export default class FooWidget extends Component {
//...
}
The code compiles, but nothing gets output when the component is being rendered.
What am I missing? How do I implement a decorator in Meteor? Is this the proper solution? What is the alternative?
Edit
I have tried this, and it still does not work
export const TestDecorator = (target) => {
console.log("*** THIS IS NOT EVEN DISPLAYED! ***");
target.prototype.componentWillMount = function () {
// ...
};
}
You are assigning your componentWillMount function to the class FooWidget instead of its prototype. Change that to target.prototype.componentWillMount = …. Besides, storing the previous componentWillMount is unnecessary in this case because it is undefined anyway.
Here is a full working example:
main.html
<head>
<title>decorators</title>
</head>
<body>
<div id="root"></div>
</body>
decorator.js
export const TestDecorator = (target) => {
console.log('Decorating…');
target.prototype.componentWillMount = function() {
console.log('Component will mount');
};
};
main.jsx
import React, { Component } from 'react';
import { render } from 'react-dom';
import { TestDecorator } from '/imports/decorator.js';
import './main.html';
#TestDecorator
class FooWidget extends Component {
render() {
return <h1>FooWidget</h1>;
}
}
Meteor.startup(function() {
render(<FooWidget/>, document.getElementById('root'));
});
.babelrc
{
"plugins": ["transform-decorators-legacy"]
}
I have been trying to display the Username of a Logged in user using Tracker React.
I have removed the auto-publish package.
/Client/components/dashboard/sidebar.jsx
import React, {Component} from 'react'
import TrackerReact from 'meteor/ultimatejs:tracker-react';
export default class Sidebar extends TrackerReact(Component) {
constructor() {
super();
this.state = {
subscription: {
users: Meteor.subscribe('users')
}
};
}
render() {
return(
<div>
<h1>{Meteor.user().username}</h1>
</div>
);
}
/Server/publications/userPublications
Meteor.publish("users", function () {
return Meteor.users.find();
});
I am getting a null object while console.log(Meteor.user()). However, I can see the current username using the Meteor DevTools for chrome.
What block of puzzle am I missing?
I doubt you can use Meteor.user(). username
Try this instead
<h1>{{currentUser}}</h1>
You can use createContainer in order to manage it.
import { Meteor } from 'meteor/meteor';
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
export class Sidebar extends Component {
static propTypes = {
loggedIn: PropTypes.bool.isRequired,
loggingIn: PropTypes.bool.isRequired,
currentUser: PropTypes.shape({
username: PropTypes.string
})
}
render() {
const { loggingIn, loggedIn } = this.props;
return (
<div>
{(() => {
if (loggingIn) {
return <Loading />
} else if (loggedIn) {
// whatever you want here.
} else {
<h1>Please Log In</h1>
}
})()}
</div>
)
}
}
export default createContainer(() => ({
user: Meteor.user(),
loggedIn: !Meteor.userId(),
loggingIn: Meteor.loggingIn()
}), Sidebar);
A few details here:
Meteor.loggingIn() is a reactive variable that is run while the user is logging in. When this is happening, there will not be a user object.
You should create a reactive container
I have the following react component that passed data to another component:
export default class App extends TrackerReact(Component){
getUserFrameData(){
return (FrameCollection.find().fetch());
}
render(){
return(
<div className="main-container">
<Frames
data={this.getUserFrameData()}
/>
</div>
);
}
}
Now I want my frames component to do an action when the component initialises.
export default class Frames extends Component{
componentDidMount(){
console.log(this.props.data);
}
render() {...}
}
But on I only get empty data at on loadup. I think it's because I'm using subscriptions and a login system. So how can I tell my Frames component to wait until everything is "loaded up"?
Use the ready method of the subscription object.
constructor() {
super();
this.state = {
sub: Meteor.subscribe('myPublication')
}
}
render() {
if (!this.state.sub.ready()) return <p>Loading...</p>;
return ...
}
http://docs.meteor.com/api/pubsub.html#Subscription-ready
I'm starting to implement the smart/dumb component pattern where the "dumb" component knows nothing about it's environment and receives all of it's data through props. What do you do when the dumb component has to submit or change data? How can it communicate with the outside world and still be "dumb"?
Here's my basic example I'm using to figure this pattern out. If I were to add and onClick event to the MyTask component that updated a counter in the DB, what would handle that event?
// components/MyList.jsx
import React from 'react';
export default class MyList extends React.Component {
render() {
return(
<div>
<h3>{this.props.listName}</h3>
<ul>
{this.props.tasks.map((task) => (
<MyTask key={task.id} task={task} />
))}
</ul>
</div>
);
}
}
MyList.propTypes = {
listName: React.PropTypes.string.isRequired,
tasks: React.PropTypes.array.isRequired,
}
export class MyTask extends React.Component {
render() {
return (
<li>{this.props.task.text}</li>
);
}
}
MyTask.propTypes = {
task: React.PropTypes.object.isRequired,
}
and the app:
// app.jsx
import React from 'react';
import MyList from './components/MyList.jsx'
export class TaskApp extends React.Component {
getList() {
return('Today Stuff');
}
getTasks() {
return([
{id: 1, text: 'foo'},
{id: 2, text: 'diggity'},
{id: 3, text: 'boo'},
{id: 4, text: 'bop'}
]);
}
render() {
return (
<MyList listName={this.getList()} tasks={this.getTasks()} />
);
}
}
Generally speaking you can handle this by passing function references from your 'smart' components down to your 'dumb' components. The dumb component then isn't responsible for implementing any of the logic associated with the function, just telling the smart component 'I've been clicked'.
In this case inside of your TaskApp class in app.jsx you could have your click handler:
//app.jsx
...
handleClick() {
// Update the DB counter by 1
}
...
render () {}
Then pass handleClick through your components as a prop:
<MyList listName={this.getList()} tasks={this.getTasks()} handleClick={this.handleClick} />
<MyTask key={task.id} task={task} handleClick={this.props.handleClick} />
And execute it in the MyTask component when a list element is clicked:
<li onClick={this.props.handleClick}>{this.props.task.text}</li>
Keep in mind that if the handleClick() function is making use of 'this' at all, you'll need to .bind(this) on your function reference when you pass it down (or bind it in the constructor / use ES6 fat arrow functions).
EDIT: For examples of the other ways to bind 'this', you could in the constructor of your class assign the bound function to your this.handleClick reference, so:
export default class TaskApp extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
...
...
}
Which allows you to use this.handleClick the way you would normally expect.
Or you could use ES6 fat arrow functions, which preserve the context of 'this' when they are called:
<MyList
listName={this.getList()}
tasks={this.getTasks()}
handleClick={() => this.handleClick} />
Assuming that TaskApp is the smart component and MyList is the dumb component, it should be something like
Smart Component
// app.jsx
import React from 'react';
import MyList from './components/MyList.jsx'
export class TaskApp extends React.Component {
getList() {
return('Today Stuff');
}
getTasks() {
return([
{id: 1, text: 'foo'},
{id: 2, text: 'diggity'},
{id: 3, text: 'boo'},
{id: 4, text: 'bop'}
]);
}
handleClick(task){
// update the db here
}
render() {
return (
<MyList listName={this.getList()} tasks={this.getTasks()}
onClick={this.handleClick}/>
);
}
}
Dumb Component
// components/MyList.jsx
import React from 'react';
export default class MyList extends React.Component {
render() {
return(
<div>
<h3>{this.props.listName}</h3>
<ul>
{this.props.tasks.map((task) => (
<MyTask onClick={() => this.props.onClick(task)}
key={task.id} task={task} />
))}
</ul>
</div>
);
}
}
MyList.propTypes = {
listName: React.PropTypes.string.isRequired,
tasks: React.PropTypes.array.isRequired,
}
export class MyTask extends React.Component {
render() {
return (
<li onClick={this.props.onClick}>{this.props.task.text}</li>
);
}
}
MyTask.propTypes = {
task: React.PropTypes.object.isRequired,
}
You can pass the event handler callback as a prop to MyTask:
<MyTask onClick={this.handleTaskClick.bind(this)} ... />
And then use it in MyTask:
<li onClick={this.props.onClick}>...</li>
See: https://facebook.github.io/react/docs/tutorial.html#callbacks-as-props