I'm using react-native-meteor to connect to Meteor server. When I run following code, I get the output as the screenshot. Connection doesn't established before the render method is called for the first time. How can I handle this? Can I block till the connection happens? ( onConnection method is not available in the react-native-meteor)
export default class App extends Component {
componentWillMount() {
console.log("GOing to connect");
Meteor.connect(SERVER_URL);
console.log("After connect : " + JSON.stringify(Meteor.status()));
}
render() {
console.log(Meteor.status());
console.log(JSON.stringify(Meteor.user()));
if (Meteor.status().status === "connected") {
if (Meteor.user()) {
return ( <
TestViewOne / >
);
} else {
return ( <
TestViewTwo / >
);
}
} else {
return ( < View > < /View>)
}
}
}
When I use the following code, the Meteor.user() still returns null.
Meteor.ddp.on('connected', function() {
console.log("on Connected : " + JSON.stringify(Meteor.user()));
localForceUpdate();
});
You need to set up the app to render a loading screen until the server is connected using withTracker, this way the main app will not progress to parts that assume the connection has been made:
class App extends Component {
constructor(props) {
super(props);
}
render() {
if (!this.appLaunched) {
if (!this.props.serverConnected || this.props.loggingIn) {
return <LoadingScreen />;
}
}
this.appLaunched = true; //this prevents the app reloading to front page everytime server reconnects
return (
<Root>
<AppContainer />
</Root>
);
}
}
export default withTracker(params => {
return {
loggingIn: Meteor.loggingIn(),
serverConnected: Meteor.status().connected
};
})(App);
Related
I have a modal window in Angular 4 that works fine but if the user clicks on the background / parent page the modal is closed.
I have found some solutions that suggest using backdrop='static' and keyboard=false when opening the modal but our modal uses a local Dialog class with a BehaviorSubject object so is opened using the .next method. I've also tried setting these attributes using div config but to no avail.
Therefore I'm looking for another solution, maybe using CSS or another setting / attribute that can be directly applied to the parent page or modal HTML.
See below for some of the relevant code.
dialog.component.ts:
constructor(private location: PlatformLocation,
private _dialog: DialogService,
private router: Router) { }
open() {
this.showDialog = true;
const body = document.body;
body.classList.add('cell-modal-open');
}
close() {
this.dialog = undefined;
}
private handleDialog(d: Dialog) {
if (!d) {
this.close();
} else if (d.template) {
if (this.showDialog) {
this.close();
}
this.dialog = d;
this.open();
}
}
ngOnInit() {
this.subscription = this
._dialog
.getDialog()
.subscribe({
next: (d) => { this.handleDialog(d); console.log('subscribed dialog') },
error: (err) => this.handleDialogError(err)
});
this.initialiseRoutingEventListeners();
}
dialog.service.ts
private d: Dialog = { template: null, size: DialogSizeEnum.XLarge };
private dialogSubject = new BehaviorSubject<Dialog>({ template: null, size: DialogSizeEnum.XLarge });
constructor() { }
showDialog(template: TemplateRef<any>, size = DialogSizeEnum.XLarge, requiresAction = false) {
Object.assign(this.d, { template: template, size: size, requiresAction: requiresAction });
if (this.d !== null) {
this.dialogSubject.next(this.d);
}
}
getDialog(): BehaviorSubject<Dialog> {
return this.dialogSubject;
}
clear() {
this.dialogSubject.next(null);
}
Any suggested approaches are welcome!
Added flag to the close() method and adding condition to only set to undefined if true (i.e. from a valid location).
(function ($) {
var webcam = {
"extern": null, // external select token to support jQuery dialogs
"append": true, // append object instead of overwriting
"width": 320,
"height": 240,
"mode": "callback", // callback | save | stream
"swffile": "../Webcam_Plugin/jscam_canvas_only.swf",
"quality": 85,
"debug": function () {},
"onCapture": function () {},
"onTick": function () {},
"onSave": function () {},
"onLoad": function () {}
};
window["webcam"] = webcam;
$["fn"]["webcam"] = function(options) {
if (typeof options === "object") {
for (var ndx in webcam) {
if (options[ndx] !== undefined) {
webcam[ndx] = options[ndx];
}
}
}
var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam["swffile"]+'" width="'+webcam["width"]+'" height="'+webcam["height"]+'"><param name="movie" value="'+webcam["swffile"]+'" /><param name="FlashVars" value="mode='+webcam["mode"]+'&quality='+webcam["quality"]+'" /><param name="allowScriptAccess" value="always" /></object>';
if (null !== webcam["extern"]) {
$(webcam["extern"])[webcam["append"] ? "append" : "html"](source);
} else {
this[webcam["append"] ? "append" : "html"](source);
}
var run = 3;
(_register = function() {
var cam = document.getElementById('XwebcamXobjectX');
if (cam && cam["capture"] !== undefined) {
/* Simple callback methods are not allowed :-/ */
webcam["capture"] = function(x) {
try {
return cam["capture"](x);
} catch(e) {}
}
webcam["save"] = function(x) {
try {
return cam["save"](x);
} catch(e) {}
}
webcam["setCamera"] = function(x) {
try {
return cam["setCamera"](x);
} catch(e) {}
}
webcam["getCameraList"] = function() {
try {
return cam["getCameraList"]();
} catch(e) {}
}
webcam["pauseCamera"] = function() {
try {
return cam["pauseCamera"]();
} catch(e) {}
}
webcam["resumeCamera"] = function() {
try {
return cam["resumeCamera"]();
} catch(e) {}
}
webcam["onLoad"]();
} else if (0 == run) {
webcam["debug"]("error", "Flash movie not yet registered!");
} else {
/* Flash interface not ready yet */
run--;
window.setTimeout(_register, 1000 * (4 - run));
}
})();
}
})(jQuery);
Above is the function which I've used in order to access the webcam of the system. It work fine when i use it on localhost but the problem arises when the same is put on the server and then accessed through intranet.
I'm unable to find the reason to fix it. Kindly help me with the same.
The first two images are the ones when i use my code on localhost. It works fine as i'm able to access the webcam.
Problem statement:
The last image is the one where I try to do the same through server. The webcam opens by the images is completely wiped out. Only a white screen appears and even if I capture the photo through webcam, the white image is only saved on server instead of a proper original image.
Because of security reasons you have to serve the Site over Https to access the camera.
Just as a preface, I am using create-react-app boiler plate.
I am trying to parse out a post from the wordpress API into a react component so I can extract all images and make them their own JSX objects. I need to have each post have its own on click method so I cant just use the dangerouslyaddHTML function in React.
Currently, I search through the string of json that had the rendered HTML from the WP content of each post and find all img tags. I then add then image src to an array and set this in my state.
However I am getting this error :
DOMException: Only secure origins are allowed
The site I have this currently hosted on it http://natalie.madeline-omoore.com/build/
The code for part of my component is below:
`componentDidMount(){
var owner;
for(var i = 0; i < this.props.categoryId.length; i++) {
if (this.props.categoryId[i].num === this.props.content.categories[0]) {
owner = this.props.categoryId[i].category;
this.setState({
catname: owner
})
break;
}
}
var theContent = this.props.content.content.rendered;
var output = $(theContent).find("img").map(function() {
return this.src;
}).get();
this.setState({
postImages: output
});
}
click(){
this.updateActive();
this.props.fix();
}
render() {
if (this.props.className === this.state.catname) {
return (
<div >
{ this.props.className === this.state.catname &&
<article className={`${this.state.catname}`} >
{this.state.postImages.map((image, i) =>
<ImageContain key={image} image={image} fix={this.props.fix} />
)}
</article>
}
</div>
);
} else {
return null;
}
}`
I am new to react so thank you!
This sounds like an issue with the 'service worker' that is default with create-react-app
You can deregister the worker by adding the following to index.js:
import { unregister } from './registerServiceWorker';
// ...
unregister();
Be sure to call unregister() after registerServiceWorker() is called.
You can learn more about this here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#making-a-progressive-web-app
Good luck, and happy coding!
I made Ionic2 App with notification using this plugin https://github.com/phonegap/phonegap-plugin-push. When the users receive the notification, depending on its data, I would like them to move the page accordingly.
I am sending route to additionalData to distinguish which page to guide them. In addition to this, I want to guide the user to specific tab of the page.
Any suggestion or advice would be appreciated!
Thank you in advance.
app.components.ts
declare var TabIndex: any;
.....
push.on('notification').subscribe((notification:any) => {
if (notification.additionalData.route == 'order-list') {
console.log('order-list is selected');
//WHAT DO I DO?
//I want the user to move to TabsPage(parent view) and its second-tab(child view)
} else if (notification.additionalData.route == 'personal') {
console.log('personal is selected');
//I want the user to move to TabsPage and its third-tab
}
});
EDITED:
app.components.ts
push.on('notification').subscribe((notification:any) => {
if (notification.additionalData.AppRoute == 'order-list') {
console.log('move to orderlist');
// this.nav.push(TabsPage, {"index" : 1});
TabIndex = 1;
} else if (notification.additionalData.AppRoute == 'order-home') {
console.log('move to home');
// this.nav.push(TabsPage, {"index" : 0});
TabIndex = 0;
}
});
tabs.ts
constructor(private navParams: NavParams) {
if (TabIndex) {
this.index = TabIndex;
}
}
You can have navParams in your Tabs.ts (as in where the tabs are mentioned and in Tabs.html, you set it using <ion-tabs>).
You can send index of tab as navParam to this tabs.ts. Then, use <ion-tabs selectedIndex="2"> in this page.
tabs.ts:
export TabsPage{
index = 1;
constructor(private navParams: NavParams){
// This if() is for other cases where you don't want to send navParams. Like normally setting this page and selectedTab to 1.
if(this.navParams.data.index !== undefined){
index = this.navParams.data.index;
}
}
}
tabs.html :
<ion-tabs selectedIndex={{index}}>
<ion-tab>..</ion-tab>
...
</ion-tabs>
And app.component.ts:
push.on('notification').subscribe((notification:any) => {
if (notification.additionalData.route == 'order-list') {
console.log('order-list is selected');
this.nav.push(TabsPage, {"index" : 2});
} else if (notification.additionalData.route == 'personal') {
console.log('personal is selected');
this.nav.push(TabsPage, {"index" : 3});
}
});
I'm doing a very simple react+redux application where I've a reducer called goals and a container called GoalsContainer.
From App Container I call the action goal for load the initial goals from a local db(indexedDB)
dispatch(loadGoals(currentDate));
This call the loadGoals from the goals actions:
export function loadGoals(currentDate = new Date()){
return dispatch => {
var goals = getGoalsFromDB(normalizeDate(currentDate)); // with this I get an array from the db
dispatch(setLoadGoals(goals));
}
}
function setLoadGoals(goals) {
return {
type: types.LOAD_GOALS,
goals
};
}
And then in my reducer I've this:
export default function goals(state = [], action) {
switch(action.type) {
case types.LOAD_GOALS:
return action.goals; // here I set the state of the goal reducer with the array passed via action
default:
console.log('Im here');
return state;
}
}
and this is my GoalsContainer(read the comments in code):
class GoalsContainer extends React.Component {
render() {
if (this.props.goals != undefined) {
console.log('ok called the render'); // in chrome console shows it
console.log(this.props.goals); // in chrome console shows correctly the goals loaded
console.log(this.props.goals.length); // it say 2
if (this.props.goals.length > 0) { // here fails...
console.log('good');
console.log(this.props.goals);
var goalsView = <div>There are goals</div>
}
else {
console.log('why go here?'); // go here
console.log(this.props.goals);
var goalsView = <div>No goals</div>
}
} else {
var goalsView = <div>Undefined</div>
}
return (
<div id="goals-main">
{goalsView}
</div>
);
}
}
GoalsContainer.propTypes = propTypes;
function mapStateToProps(state) {
const { goals, environment } = state;
const { currentDate } = environment;
return {
goals,
currentDate
}
}
export default connect(mapStateToProps)(GoalsContainer);
The problem is that when it does the if check, it fails(like if there are 0 goals), but in chrome console show correctly the goals array...
Then if I force with some workaround the render(), all works correctly.
What I've done wrong ?
You didn't mention if you use https://github.com/gaearon/redux-thunk or not. To use reducer returning function you should definitely install it.
It's hard to follow all of the parts of your code from random gists. What happens if you change your GoalsContainer to be;
class GoalsContainer extends React.Component {
render() {
console.log(this.props.goals);
return (
<div id="goals-main">
{(this.props.goals.length >= 1)?<div>There are goals</div>:<div>Nope!</div>}
</div>
);
}
}
What gets logged to the console?