Meteor does not display collection that exists in db - mongodb

A Meteor/React noob here, going through the Meteor-React tutorial and got stuck on step 3. My problem is that the data is not being displayed in the browser, although it exists in the db.
Here is my imports/ui/App.jsx:
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>Todo List</h1>
</header>
<ul>
{this.renderTasks()}
</ul>
</div>
);
}
}
App.propTypes = {
tasks: PropTypes.array.isRequired,
};
export default createContainer(() => {
return {
tasks: Tasks.find({}).fetch(),
};
}, App);
No errors show up in console.
Basically this.props.tasks returns empty array. But db.tasks.find({}) in console shows records. Without changing much around, if I hardcode Tasks records, they display alright, so the issue isn't with Task component. Anyone can help here? Would much appreciate.
client/main.jsx:
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import App from '../imports/ui/App.jsx';
Meteor.startup(() => {
render(<App />, document.getElementById('render-target'));
});
package.json:
{
"name": "simple-todos",
"private": true,
"scripts": {
"start": "meteor run"
},
"dependencies": {
"meteor-node-stubs": "~0.2.0",
"react": "^15.1.0",
"react-addons-pure-render-mixin": "^15.1.0",
"react-dom": "^15.1.0"
}
}
npm version 3.3.12
node version 5.6.0

As of your description from, it seems that your database is not accessible on both server & client. May be you forgot to add the reference of your database in the server side. try to import your tasks main.js file of your server.
Make sure your server/main.js has the following line:
import '../imports/api/tasks.js';

Related

React App deployed in LWC component of salesforce

I have deployed React App in LWC component without using Aura container basically bundle react application with webpack as static resource and use them inside a LWC and able to render.
able to open individual stylesheet for debugging purpose.
Question: Not able to debug the code/not opening individual JS file/component in developer console.
lwcReactContainer.html
<template>
<div id="react-app-root"></div>
</template>
lwcReactContainer.js
import { LightningElement, wire } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import SPMLayoutEditor1 from '#salesforce/resourceUrl/SPMLayoutEditor1';
//import myStaticStyles from '#salesforce/resourceUrl/myStaticStyles';
import {
APPLICATION_SCOPE,
createMessageContext,
MessageContext,
publish,
releaseMessageContext,
subscribe,
unsubscribe,
} from 'lightning/messageService';
import getContactList from '#salesforce/apex/ContactController.getContactList';
export default class LWCReactContainer extends LightningElement {
renderedCallback() {
this.apiInProgress = true;
Promise.all([
loadScript(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/js/main.js'),
loadStyle(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/css/main.css'),
this.getUserInfo(), this.getContactList(), this.fetchObjectList()
]).then((data) => {
const contacts = data[3];
mount(this.template.querySelector('div'), { contacts });
});
}

SvelteKit console error "window is not defined" when i import library

I would like to import apexChart library which using "window" property, and i get error in console.
[vite] Error when evaluating SSR module /src/routes/prehled.svelte:
ReferenceError: window is not defined
I tried use a apexCharts after mount, but the error did not disappear.
<script>
import ApexCharts from 'apexcharts'
import { onMount } from 'svelte'
const myOptions = {...myOptions}
onMount(() => {
const chart = new ApexCharts(document.querySelector('[data-chart="profit"]'), myOptions)
chart.render()
})
</script>
I tried import a apexCharts when i am sure that browser exist.
import { browser } from '$app/env'
if (browser) {
import ApexCharts from 'apexcharts'
}
But i got error "'import' and 'export' may only appear at the top level"
I tried disable ssr in svelte.config.js
import adapter from '#sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter(),
prerender: {
enabled: false
},
ssr: false,
}
I tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists
{ #if browser }
<ProfitChart />
{ /if }
Nothing helped.
Does anyone know how to help me please?
The easiest way is to simply include apexcharts like a standalone library in your webpage like this:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
And then simply use it in the onMount:
onMount(() => {
const chart = new ApexCharts(container, options)
chart.render()
})
You can add this line either in your app.html or include it where it's required with a <svelte:head> block.
An alternative way would be to dynamically import during onMount:
onMount(async () => {
const ApexCharts = (await import('apexcharts')).default
const chart = new ApexCharts(container, options)
chart.render()
})
As an extra: use bind:this instead of document.querySelector to get DOM elements, that would be the more 'svelte' way.
I have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window
Install vite plugin: npm i -D vite-plugin-iso-import
Add plugin to svelte.config.js:
kit: {
vite: {
plugins: [
isoImport(),
],
Add plugin to TypeScript config (if you use TS):
"compilerOptions": {
"plugins": [{ "name": "vite-plugin-iso-import" }],
Use as normal but note the "?client" on the import:
<script context="module">
import { chart } from 'svelte-apexcharts?client';
import { onMount } from 'svelte'
let myOptions = {...myOptions}
onMount(() => {
myOptions = {...updated options/data}
});
</script>
<div use:chart={myOptions} />
Debugging note:
To have import not highlighting as an error temporarily, just:
npm run dev, your project will compile fine, then test in browser to execute at least once.
remove ?client now, save and continue debugging as usual.
For all of you trying to import dynamically into a js or ts file, try the following:
Import your package during on mount in any svelte component.
onMount(async () => {
const Example = await import('#creator/examplePackage');
usePackageInJSOrTS(Example.default);
});
Use the imported package in your js/ts function. You need to pass the default value of the constructor.
export function usePackageInJsOrTs(NeededPackage) {
let neededPacakge = new NeededPackage();
}

How to onRowClick redirected to another page with mui-datatables npm package?

I have a react app that uses package mui-datatables. I want to be redirected to "/edit-form" onRowClick, but it didn't work (nothing happens, no errors either).
import React, { Component } from "react";
import { Link as RouterLink } from "react-router-dom";
import Link from "#material-ui/core/Link";
import MUIDataTable from "mui-datatables";
class DataTable extends Component {
state={...}
redirectToForm = props => <RouterLink to="/edit-form" {...props}/>
render() {
const options = {
onRowClick: rowData => this.redirectToForm(rowData)
};
return (
<Link
color="secondary"
className={classes.button}
component={this.goToDetailedTable}
>
Detail
</Link>
<MUIDataTable
title={title}
columns={value.state.columnName}
data={value.state.rowData}
options={options}
/>
)
}
When I console.log(rowData), it did print out the row data:
const options = {
onRowClick: rowData => console.log(rowData)
};
Instead of using <Link/> try calling history from the history package and then just history.push('edit/form').

Using mongodb-stitch library in Angular 4

Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.
There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using #types) to no avail.
Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.
The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts
import { Component, OnInit } from "#angular/core";
import { StitchClientFactory } from "mongodb-stitch";
let appId = 'authapp-****';
#Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})
export class MongoAuthComponent implements OnInit {
mClient;
ngOnInit() {
this.mClient = StitchClientFactory.create(appId);
}
And you can then use this for whatever purpose you want, such as for implementing sign-in with Google
gLogin(){
this.mClient.then(stitchClient => {
stitchClient.authenticate("google");
})
not sure whether the question is still relevant considering it was asked two months ago but anyway...
As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any
For example:
declare var stitch: any;
export class MyService implements OnInit {
db;
client;
ngOnInit() {
this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
this.client.login();
}
save() {
this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
}
}
the previous answers are functional, but i wanna share a example using a service injectable.
service.ts
import { Injectable } from '#angular/core';
import { Jsonp, URLSearchParams } from '#angular/http';
import { StitchClientFactory } from "mongodb-stitch";
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private jsonp: Jsonp) { }
client;
connect(){
this.client = new StitchClientFactory.create("App ID"); // Slitch apps > Clients > App ID
this.client.then(stitchClient => stitchClient.login())
.then((stitchClient) => console.log('logged in as: ' + stitchClient))
.catch(e => console.log('error: ', e));
}
all() {
this.connect();
return this.client.then(stitchClient => {
let db = stitchClient.service('mongodb', 'mongodb-atlas').db("database Name"); // Slitch apps > mongodb-atlas > Name database.Collection
let itemsCollection = db.collection('name collection'); // Slitch apps > mongodb-atlas > Name database.Collection
console.log(itemsCollection.find().execute());
return itemsCollection.find().execute();
})
.then(result => {return result})
.catch(e => console.log('error: ', e));
}
}
after make the previous file, you must create a module to receive the data, so:
module.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { StitchClientFactory } from "mongodb-stitch";
import { Service } from 'service'; // previous code
declare var stitch: any;
#Component({
template: '
<ul class="demo-list-icon mdl-list">
<li class="mdl-list__item" *ngFor="let item of data | async">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-icon">{{propiedad.nombre}}</i>
</span>
</li>
</ul>
'
})
export class MainComponent implements OnInit {
data: Observable<[]>;
constructor(private Service: service) {
}
ngOnInit() {
this.propiedades = this.Service.all();
}
}
important, you don´t must forget to add service on module.ts intitial declarations.
mongodb Atlas
mongodb-stitch vía NPM
Documentation mongoDB Stitch.
Sure!

Meteor can't subscribe to TAPi18n.Collection using TAPi18n.subscribe

I am using Meteor 1.5 and I am trying to subscribe to an i18n collection using these packages :
TAP:i18n
TAP:i18n-db
I ran meteor create --full <appname> to have the full scaffolded app.
Then I removed insecure and autopublish packages and added aldeed:simple-schema, audit-argument-checks and mdg:validated-method as recommended security mesures.
// imports/startup/server/fixtures.js
import { Meteor } from 'meteor/meteor';
import { Links } from '../../api/links/links.js';
Meteor.startup(() => {
// if the Links collection is empty
if (Links.find().count() === 0) {
const data = [
{
title: 'Do the Tutorial',
url: 'https://www.meteor.com/try',
i18n: {
'fr': {
title: 'FR Do the Tutorial',
},
},
createdAt: new Date(),
},
{
...
},
];
data.forEach(link => Links.insert(link));
}
});
// imports/api/links/links.js
import { Mongo } from 'meteor/mongo';
export const Links = new TAPi18n.Collection('links');
// imports/api/links/server/publications.js
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/tap:i18n';
import { Links } from '../links.js';
TAPi18n.publish('links.all', function () {
return Links.i18nFind();
});
// client/main.js
import { TAPi18n } from 'meteor/tap:i18n';
import '/imports/startup/client';
import '/imports/startup/both';
Meteor.startup(function() {
TAPi18n.setLanguage('en');
});
// imports/ui/components/info/info.js
import { Links } from '/imports/api/links/links.js';
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/tap:i18n';
import './info.html';
Template.info.onCreated(function () {
TAPi18n.subscribe('links.all');
});
Template.info.helpers({
links() {
return Links.find({});
},
});
...
In Chrome console using Meteor Dev-Tool, I can see this :
Chrome Meteor Dev-Tool screenshot
Basically it says unsubscribed from links.all (unrecognized subscription)
In the server console, I can see this :
Meteor Server Console
I did some work to include check statement in links.js above but even when I check all fields, the app can't subscribe to the publication.
Any idea or help would be much appreciated.
The packages are not mandatory for me if there is a better example/repo somewhere I can actually look at.
I thought you could not mix them up together. Use either TAP:i18n-db or TAP:i18n.
For examples have a look at the git repositories:
https://github.com/TAPevents/tap-i18n
https://github.com/TAPevents/tap-i18n-db
There are several examples you can have a look and decide to use only one of the packages.