Adding a new card to the DB - node.js

I am trying to add a new card to the database.
I have a page in React that when a user fills the form and clicks "Next", a new user is created and added to the Database.
The next page is Business Information he needs to fill, but when he clicks on "Create Card" it doesn't do anything and the Database remains empty.
This is the code for my BusinessRegistrationPage.js:
import {toast} from 'react-toastify';
import {Container} from 'react-bootstrap';
import SimpleRegistrationComp from "../components/simple-registration/SimpleRegistrationComp";
import CreateCardComp from '../components/my-cards/CreateCardComp';
import {useState} from 'react';
function BusinessRegistrationPage () {
const[isStep1,setIsStep1]= useState(true);
return <Container>
{isStep1&&
<SimpleRegistrationComp clickHandler={registerUser}
text="Next" >
</SimpleRegistrationComp>
}
{
!isStep1&& <CreateCardComp clickHandler={createCard} ></CreateCardComp>
}
</Container>;
function registerUser(data) {
registerNewAccount(data,
(data)=>{
if(data._id){
toast('Account Created Successfully');
setIsStep1(false);
}
else
{
toast('Eror Acount was not created');
}
});
}
function createCard() {
alert('create card');
}
}
export default BusinessRegistrationPage;```

Related

How to determine if "click" or "box-select" was used with Streamlit/Plotly to return data from chart to Streamlit

I'm not a Javascript/Typescript/React dev. I'm hacking my way through this for a work project.
I'm using Streamlit, with plotly.
I'm hacking the basic code from streamlit-plotly-events.
I was trying to have the click or box-select information passed back with the data selected via the plotlyEventHandler() (see code below.) However, both this.props.args["click_event"] and this.props.args["select_event"] are true, regardless of whether you use box-select in the plotly chart, or click a single data point in the chart.
I thought of assuming if there is only one data point, then it was a click - but you can box select only one data point.
// import React, {useState,useEffect} from "react"
import React, { ReactNode } from "react"
//import React from "react"
import {
StreamlitComponentBase,
withStreamlitConnection,
Streamlit,
// ComponentProps,
} from "streamlit-component-lib"
import Plot from "react-plotly.js"
class StreamlitPlotlyEventsCapture extends StreamlitComponentBase {
public render = (): ReactNode => {
// Pull Plotly object from args and parse
const plot_obj = JSON.parse(this.props.args["plot_obj"]);
const override_height = this.props.args["override_height"];
const override_width = this.props.args["override_width"];
// Event booleans
const click_event = this.props.args["click_event"];
const select_event = this.props.args["select_event"];
const hover_event = this.props.args["hover_event"];
Streamlit.setFrameHeight(override_height);
return (
<Plot
data={plot_obj.data}
layout={plot_obj.layout}
config={plot_obj.config}
frames={plot_obj.frames}
onClick={click_event ? this.plotlyEventHandler : function(){}}
onSelected={select_event ? this.plotlyEventHandler : function(){}}
onHover={hover_event ? this.plotlyEventHandler : function(){}}
style={{width: override_width, height: override_height}}
className="stPlotlyChart"
/>
)
}
/** Click handler for plot. */
private plotlyEventHandler = (data: any) => {
// Build array of points to return
var clickedPoints: Array<any> = [];
//const util = require('util')//#33333 used with util.inspect(arrayItem) below
// I dont know why we can't directly use "this.variables" in the clickedPoints.push
// but we can't, so we create the variables here.
var wasClicked = this.props.args["click_event"];
var wasSelected = this.props.args["select_event"];
var wasHovered = this.props.args["hover_event"];
data.points.forEach(function (arrayItem: any) {
// console.log(util.inspect(arrayItem, {maxArrayLength: null, depth:null }))
clickedPoints.push({
// I dont know why we can't directly use "this.variables" here, but we can't
// so we use the variables created above.
clicked:wasClicked,
selected:wasSelected,
hovered:wasHovered,
x: arrayItem.x,
y: arrayItem.y,
curveNumber: arrayItem.curveNumber,
pointNumber: arrayItem.pointNumber,
pointIndex: arrayItem.pointIndex
})
});
// Return array as JSON to Streamlit
Streamlit.setComponentValue(JSON.stringify(clickedPoints))
}
}
export default withStreamlitConnection(StreamlitPlotlyEventsCapture)

How to implement useContext (React Native, Expo) to control weather unit settings?

I am trying to implement the ability to switch between imperial and metric units using the useContext() hook. So far, I have not had much success. I have read the React useContext() documentation and followed this article. This is my current JavaScript source code that currently does not function as intended:
App.js - where context provider is located
import React from 'react';
import WeatherScreen from './components/screens/WeatherScreen';
import { CurrentUnitContext } from './components/hooks/CurrentUnitContext.js';
export default App = () => {
return (
<CurrentUnitContext.Provider
value={"imperial"}
>
<WeatherScreen />
</CurrentUnitContext.Provider>
);
};
CurrentUnitContext.js - Intended for createContext()
import { createContext } from 'react';
/**
* WIP custom hook for setting current unit
*
* todo - change weather units here
* set imperial (F), metric (C), and maybe standard (K)
*/
export default CurrentUnitContext = createContext();
/**
export default CurrentUnitContext = createContext({
theCurrentUnit: "imperial",
setTheCurrentUnit: () => {},
});
*/
UnitSwitch.js - Intended to contain the component to set the units with user feedback.
import React, { useState, useEffect, useContext } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { CurrentUnitContext } from '../../hooks/CurrentUnitContext.js';
import { tailwind, fontConfig } from '../../../tailwind.js';
/**
* Unit Switcher child component. Based on switch's boolean
* value useState hook isEnabled, set useEffect hook currentUnit
* to either "imperial" or "metric".
*
* #param - switchHeader: Displays the unit switch header
* text passed from WeatherContent.js
* #param - imperialUnits: Text passed from WeatherContext.js for
* imperial unit button string.
* #param - metricUnits: Text passed from WeatherContext.js for
* metric unit button string.
*/
export default UnitSwitch = ({ imperialUnits, metricUnits, switchHeader }) => {
const [theCurrentUnitSetting, setTheCurrentUnitSetting] = useState("imperial");
return (
<View style={tailwind('bg-gray-300 border-t-2 p-3 w-64 h-48')}>
<Text style={tailwind('text-center text-22fz')}>
{switchHeader}
</Text>
<View style={tailwind('flex-1 justify-center items-center')}>
<TouchableOpacity
style={tailwind('')}
onPress={() => setTheCurrentUnitSetting("metric")}
>
<Text style={tailwind('')}>
{metricUnits}
</Text>
</TouchableOpacity>
</View>
</View>
);
};
getWeather.js - Hook designed to fetch weather
import { useState, useEffect, useContext } from 'react';
import useLocation from '../hooks/useLocation.js';
import { CurrentUnitContext } from './CurrentUnitContext.js';
/**
* #getWeather - if permission was granted in useLocation() hook,
* uses Object theLocation containing lat. and long. coordinates as
* decimal number values. Returns the currentWeather. useEffect()
* relies on the value of Object theLocation.
*
* #WEATHER_API_KEY - accessed from clientSecret directory,
* hidden for repo security and must be manually provided.
* #currentWeather - useState hook to store JSON result of
* current weather data.
* #baseWeatherUrl - initial OpenWeatherMap API access string
* #weatherUrl - Full OpenWeatherMap API access string
*/
export default getWeather = () => {
const theLocation = useLocation();
const theCurrentUnit = useContext(CurrentUnitContext);
const [currentWeather, setCurrentWeather] = useState();
useEffect(() => {
const { WEATHER_API_KEY } = require("../clientSecret/openWeather.json");
let baseWeatherUrl = 'https://api.openweathermap.org/data/2.5/weather?',
weatherUrl = "";
//console.log(theLocation); //confirm we are getting location, uncomment if needed
if (theLocation !== undefined) {
weatherUrl = `${baseWeatherUrl}lat=${theLocation.latitude}&lon=${theLocation.longitude}&units=${theCurrentUnit}&appid=${WEATHER_API_KEY}`;
console.log(weatherUrl); //uncomment if needed
const fetchWeather = async () => {
try {
const response = await fetch(weatherUrl);
const result = await response.json();
if (response.ok) {
setCurrentWeather(result);
} else {
alert(result.message);
};
} catch (error) {
console.log(error);
alert(error.message);
} finally {
console.log("async function fetchWeather() has been run."); //API rate call confirmation
};
};
//API calls must not occur more than once every minute.
fetchWeather();
};
}, [theLocation, theCurrentUnit]);
return currentWeather;
};
As shown right now, the error message that appears is:
TypeError: undefined is not an object (evaluating >'_CurrentUnitContext.CurrentUnitContext.Provider')
This error is located at:
in App (created by ExpoRoot)
in ExpoRoot (at renderApplication.js:45)
in RCTView (at View.js:34)
in View (at AppContainer.js:106)
in RCTView (at View.js:34)
in View (at AppContainer.js:132)
in AppContainer (at renderApplication.js:39)
I was assisted, in CurrentUnitContext.js, changing
export default CurrentUnitContext = createContext();
to
export let CurrentUnitContext = createContext();
fixed the error.

How to share UI state in single-spa using RxJs?

As per the single-spa official doc, we can share the application's UI state by using RxJs.
Observables / Subjects (RxJs) - one microfrontend emits new values to
a stream that can be consumed by any other microfrontend. It exports
the observable to all microfrontends from its in-browser module, so
that others may import it.
Link: https://single-spa.js.org/docs/recommended-setup/#ui-state
Link: https://single-spa.js.org/docs/faq/#how-can-i-share-application-state-between-applications
I was trying to create an example in React, where I am using single-spa parcel to include my micro-apps in root application. I was trying to share the UI state using RxJs.
When I googled it for single-spa RxJs, I didn't find anything. Can anyone provide me a basic example where I will be able to share UI state for below use cases:
Sharing the UI state from root app to my micro-apps.
Sharing the UI state from micro-apps to root apps.
Sharing the UI state between micro-apps.
Here is a high level overview on how to approach this:
add rxjs as a shared dependency in your import map
"rxjs": 'https://unpkg.com/#esm-bundle/rxjs/system/rxjs.min.js,
"rxjs/operators": 'https://unpkg.com/#esm-bundle/rxjs/system/rxjs-operators.min.js,
consider pinning these to a specific version!
create a utility module (create-single-spa makes this easy!) that sets up and exports the observable with data that you need
include this utility module in importmap too
import and subscribe to observable from the utility module in the apps that need it
don't forget to unsubscribe when your apps unmount.
celebrate 🎉
I have created single-spa-example-rxjs-shared-state as an example repo that shows how to use an Rxjs utility module with cross-frontend imports.
This does the trick
In root html js file add the following
Import { Subject, Subscription } from 'https://dev.jspm.io/rxjs#6/_esm2015';
import { filter, map } from 'https://dev.jspm.io/rxjs#6/_esm2015/operators';
export class EventBusService {
constructor() {this.subject$ = new Subject(); }
emit(event) {
this.subject$.next(event);
}
on(eventName, action) {
return this.subject$.pipe(
filter( (e) => e.name === eventName),
map( (e) => e["data"])).subscribe(action);
}
}
var EventBus= new EventBusService()`enter code here`;
System.import('single-spa').then(function (singleSpa) {
singleSpa.registerApplication(
'app1',
function () {
return System.import('app1');
},
function (location) {
return true;
// return location.pathname.startsWith('/app1');
},
{ EventBus: EventBus }
);
singleSpa.registerApplication(
'app2',
function () {
return System.import('app2');
},
function (location) {
return true
// return location.pathname.startsWith('/app2');
},
{ EventBus: EventBus }
)
singleSpa.start();
})
In component
import { Component,OnInit ,ChangeDetectorRef} from '#angular/core';
import { assetUrl } from 'src/single-spa/asset-url';
import { singleSpaPropsSubject, SingleSpaProps } from 'src/single-spa/single-spa-props';
import { Subscription } from 'rxjs';
#Component({
selector: 'app1-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
singleSpaProps: SingleSpaProps;
subscription: Subscription;
title = 'app1';
yoshiUrl = assetUrl("yoshi.png");
msgFromMicro="";
titleToPass="";
constructor(private ChangeDetectorRef:ChangeDetectorRef){
}
ngOnInit(): void {
this.subscription = singleSpaPropsSubject.subscribe(
props => {
this.singleSpaProps = props;
console.log(props);
this.lookForEvents();
}
);
}
lookForEvents(){
this.singleSpaProps['EventBus'].on('msgFrmMicro2',(data)=>{
this.msgFromMicro=data;
this.ChangeDetectorRef.detectChanges();
});
}
sendMsg(){
// alert(this.titleToPass);
debugger;
this.singleSpaProps['EventBus'].emit({name:'msgFrmMicro1',data:this.titleToPass});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
Take look at the following repo, handled the same scenario by passing observable ref to micro apps through customprops of single spa
https://github.com/SENTHILnew/micro_spa_intercom

Setting up a test Database for jest tests on Nodejs

I am quite new to Testing with jest and was learning to write tests for my code. The current setup is :
//cityService.ts:
import {inject, injectable} from "inversify";
import {NUCLEUS_TYPES} from "../nucleus/NUCLEUS_TYPES";
import {AppLogger} from "../libs/logger";
import {CityReadOnlyDao, CityReadWriteDao} from "../nucleus/daos/cityDao";
import {ICityAttributes} from "../nucleus/interfaces/attributeInterfaces";
import {ICityModel} from "../nucleus/interfaces/modelInterfaces";
import {BaseService} from "../nucleus/services/baseService";
import {escapeRegExp} from "../utils/helper";
import {SortOrder} from "../nucleus/constants/enums";
#injectable()
export class CityService extends BaseService<ICityModel, ICityAttributes>{
constructor(#inject(NUCLEUS_TYPES.AppLogger) protected appLogger: AppLogger,
#inject(NUCLEUS_TYPES.ReadOnlyDao.City) protected cityReadOnlyDao: CityReadOnlyDao,
#inject(NUCLEUS_TYPES.ReadWriteDao.City) protected cityReadWriteDao: CityReadWriteDao){
super(cityReadOnlyDao, cityReadWriteDao);
}
async suggestCity(req) {
this.appLogger.debug(typeof req.body.query);
let regQuery = new RegExp(escapeRegExp(req.body.query.trim()), 'i');
let cities = await this.find({
condition: {'name': {$regex: regQuery}},
sortField: 'used',
sortOrder: SortOrder.DESC,
count: (req.body.limit ? Number(req.body.limit) : 10),
start: (req.body.skip ? Number(req.body.skip) : 0)
});
return ({state: true, cities});
}
}
And a sample test is :
import { CityService } from "../src/services/cityService";
import container from "../src/libs/ioc";
let cityService = container.get<CityService>(TYPES.Service.City);
test("Testing with full Name", async () => {
expect.hasAssertions();
let response = await cityService.suggestCity({
body: {
query: 'London'
}
});
expect(response.cities).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'London' })]));
});
The test runs and passes without a hitch. Now my doubt was that I am hitting my database with this test. Is there a way to test this without the function calling my database? Perhaps Making a mock database. Can someone point me in the right direction as to how should I proceed with it?

Cant show name of logged-in user - angular2 -meteor

I just want to show the name of the current logged in user, but I cant make it works.
I wrote this on the app.component:
import { Component } from '#angular/core';
import template from './app.component.html';
import {ROUTER_DIRECTIVES} from '#angular/router';
import {LoginButtons} from 'angular2-meteor-accounts-ui';
//import our Carousel Component
import {CSSCarouselComponent} from './imports/componenets/carousel/carousel.component';
import { InjectUser } from 'angular2-meteor-accounts-ui';
#Component({
selector: 'app',
template,
directives: [ROUTER_DIRECTIVES, LoginButtons,CSSCarouselComponent]
})
#InjectUser('user')
export class AppComponent {
user: Meteor.User;
constructor() {
console.log(this.user);
}
loginFacebook(event) {
Meteor.loginWithFacebook({}, function(err){
if (err) {
throw new Meteor.Error("Facebook login failed");
}
console.log(Meteor.user().profile.name;);
});
}
}
console.log(this.user); returns undefined.
console.log(Meteor.user().profile.name;); works and gives me the name, but I have no success to export it to the html and show that.
You have to reference Meteor in your Component, for example as let M = Meteor;. Then you can use {{M.user().profile.name}} in your html.
Also this.user is never set in your code, you just define its class. Anyway, you should always use Meteor.user() or M.user(), because it's always up-to-date.

Resources