I tried to google some guides or tutorials and didn't found any. Is there any way to integrate into my react-native app a Parse SDK same as to android and iOS way? Because I tried to integrate Parse-SDK-JS and it didn't work now my app, crashing with error Error: Unable to resolve module crypto from node_modules\parse\node_modules\crypto-js\core.js: crypto could not be found within the project.'
my code:
parse.ts:
// In a React Native application
import Parse, { Error } from 'parse';
// On React Native >= 0.50 and Parse >= 1.11.0, set the Async
import { AsyncStorage } from 'react-native';
export const initParse = () => {
Parse.setAsyncStorage(AsyncStorage);
Parse.initialize('xxxxxxxxxxxxxxxxxxxxxxxxxxx'); //APP_ID
Parse.serverURL = 'https://xxx.herokuapp.com/parse'; //HEROKU URI SERVER
};
export const testCreate = () => {
const GameScore = Parse.Object.extend('GameScore');
const gameScore = new GameScore();
gameScore.set('score', 1337);
gameScore.set('playerName', 'Sean Plott');
gameScore.set('cheatMode', false);
gameScore.save().then(
(gameScore: any) => {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
(error: Error) => {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
alert('Failed to create new object, with error code: ' + error.message);
},
);
};
index.js:
/**
* #format
*/
import {
AppRegistry
} from 'react-native';
import {
initParse
} from './src/library/parse/parse';
import App from './App';
import {
name as appName
} from './app.json';
initParse();
AppRegistry.registerComponent(appName, () => App);
You need to import Parse from parse/react-native.js. It should be something like this:
import Parse, { Error } from 'parse/react-native.js';
Related
I am trying to used Azure AD to integrate my application, but I keep getting this error
AuthError.ts:49 Uncaught (in promise) BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. For more visit: aka.ms/msaljs/browser-errors.
at BrowserAuthError.AuthError [as constructor] (AuthError.ts:49:1)
at new BrowserAuthError (BrowserAuthError.ts:195:1)
at BrowserAuthError.createInteractionInProgressError (BrowserAuthError.ts:276:1)
at BrowserCacheManager.setInteractionInProgress (BrowserCacheManager.ts:1000:1)
at ClientApplication.preflightInteractiveRequest (ClientApplication.ts:837:1)
at ClientApplication.preflightBrowserEnvironmentCheck (ClientApplication.ts:820:1)
at PublicClientApplication.<anonymous> (ClientApplication.ts:272:1)
at step (vendors~main.chunk.js:217:19)
at Object.next (vendors~main.chunk.js:147:14)
at vendors~main.chunk.js:119:67
at new Promise (<anonymous>)
at __awaiter (vendors~main.chunk.js:98:10)
at ClientApplication.acquireTokenRedirect (ClientApplication.ts:268:1)
at index.tsx:50:1
This is my index.tsx file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import '#scuf/common/honeywell/theme.css';
import '#scuf/datatable/honeywell/theme.css';
import store from './stores';
import { Provider } from 'mobx-react';
import createRouter from './router';
import './index.scss';
import { msalConfig } from "./stores/authConfig";
import { MsalProvider, MsalAuthenticationTemplate } from "#azure/msal-react";
import { InteractionRequiredAuthError, AuthError } from "#azure/msal-common";
import { PublicClientApplication, InteractionType } from "#azure/msal-browser";
const msalInstance = new PublicClientApplication(msalConfig);
msalInstance.handleRedirectPromise()
.then((redirectResponse) => {
if (redirectResponse !== null) {
// Acquire token silent success
let accessToken = redirectResponse.accessToken;
console.log(accessToken)
// Call your API with token
} else {
// MSAL.js v2 exposes several account APIs, logic to determine which account to use is the responsibility of the developer
const activeAccount = msalInstance.getActiveAccount();
const accounts = msalInstance.getAllAccounts();
if (!activeAccount && accounts.length === 0) {
console.error("User not logged in!!!");
}
const accessTokenRequest = {
scopes: ["user.read", "openid"],
account: activeAccount || accounts[0],
// roles: ["rca.approver"],
};
msalInstance
.acquireTokenSilent(accessTokenRequest)
.then(function (accessTokenResponse) {
// Acquire token silent success
// Call API with token
let accessToken = accessTokenResponse.accessToken;
console.log(accessToken)
// Call your API with token
})
.catch(function (error) {
//Acquire token silent failure, and send an interactive request
console.log(error);
if (error instanceof InteractionRequiredAuthError || error instanceof AuthError) {
msalInstance.acquireTokenRedirect(accessTokenRequest);
}
});
}
})
// Here we are importing our stores file and spreading it across this Provider. All stores added to this will be accessible via child injects
const wrappedApp = (
<MsalProvider instance={msalInstance}>
<MsalAuthenticationTemplate interactionType={InteractionType.Redirect}>
<Provider store={store}>
<App />
</Provider>
</MsalAuthenticationTemplate>
</MsalProvider>
);
// Here the router is bootstrapped
const router = createRouter();
router.start(() => {
ReactDOM.render(wrappedApp, document.getElementById('root') as HTMLElement);
});
and this is my authConfig.js:
export const msalConfig = {
auth: {
clientId: "XXX",
authority: "https://login.microsoftonline.com/YYY",
redirectUri: "http://localhost:3000",
postLogoutRedirectUri: "http://localhost:3000",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
// Add scopes here for ID token to be used at Microsoft identity platform endpoints.
export const loginRequest = {
scopes: ["User.Read","openid"],
redirectUri: "http://localhost:3000",
};
// Add the endpoints here for Microsoft Graph API services you'd like to use.
export const graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};
I have tried the solution in net but it still gives me the same error. These are the only two files in my project folder that deals with MSAL packages. Did I miss anything? As I learnt from the documenatation, interactionType redirects to AD authentication on which token is generated which could then be sent to APIs. Please correct me if I am wrong.
I'm looking at this page https://docs.aws.amazon.com/sdk-for-javascript... and it seems to imply that the SDK will look at ~/.aws/credentials and take the [default] profile if there is no AWS_PROFILE environment var.
I'm running a NextJS app on my local machine trying to list S3 buckets, getting Error: Credential is missing.
I would really love not to have to specify the creds in env vars as I'll be deploying the app to ECS later where it will use an IAM Role for access.
Here's my code:
import { ListBucketsCommand } from '#aws-sdk/client-s3';
import React, { useEffect } from 'react';
import { s3Client } from '../lib/s3Client';
const S3Buckets = () => {
useEffect(() => {
async function getS3Buckets() {
const input = {};
const command = new ListBucketsCommand(input);
const res = await s3Client.send(command);
console.log(res);
}
getS3Buckets();
}, []);
return <div>{/* S3 Buckets eventually listed here */}</div>;
};
export default S3Buckets;
with the s3Client helper as below:
import { S3Client } from '#aws-sdk/client-s3';
export const s3Client = new S3Client({ region: process.env.AWS_REGION });
the problem
I created a Shopify node.js app using the Shopify CLI and I want to display a simple bar under the header using a script tag. I used the script tag API to add a script tag
"script_tags": [
{
"id": 174240039086,
"src": "https://xxxxx.ngrok.io/script_tag",
}
]
And I also added a <div id="script-app"></div> into the theme, under the header.
Here is my script_tag.js file, located in /pages/script_tag.js
import ReactDOM from 'react-dom';
class TestScriptTag extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<p>this is a bar</p>
</div>
);
}
}
ReactDOM.render(<TestScriptTag />, document.getElementById('script-app'));
export default TestScriptTag;
Lastly, here is my server.js (most of it is what came with the CLI):
import "#babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "#shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "#shopify/shopify-api";
import Koa from "koa";
import next from "next";
import Router from "koa-router";
import { flushSync } from "react-dom";
const fs = require('fs');
dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8083;
const dev = process.env.NODE_ENV !== "production";
const app = next({
dev,
});
const handle = app.getRequestHandler();
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
API_VERSION: ApiVersion.October20,
IS_EMBEDDED_APP: false,
// This should be replaced with your preferred storage strategy
SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});
// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};
app.prepare().then(async () => {
const server = new Koa();
const router = new Router();
server.keys = [Shopify.Context.API_SECRET_KEY];
server.use(
createShopifyAuth({
async afterAuth(ctx) {
console.log("here")
// Access token and shop available in ctx.state.shopify
const { shop, accessToken, scope } = ctx.state.shopify;
const host = ctx.query.host;
ACTIVE_SHOPIFY_SHOPS[shop] = scope;
const response = await Shopify.Webhooks.Registry.register({
shop,
accessToken,
path: "/webhooks",
topic: "APP_UNINSTALLED",
webhookHandler: async (topic, shop, body) =>
delete ACTIVE_SHOPIFY_SHOPS[shop],
});
if (!response.success) {
console.log(
`Failed to register APP_UNINSTALLED webhook: ${response.result}`
);
}
// Redirect to app with shop parameter upon auth
ctx.redirect(`/?shop=${shop}&host=${host}`);
},
})
);
const handleRequest = async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
ctx.res.statusCode = 200;
};
router.get("/", async (ctx) => {
const shop = ctx.query.shop;
// This shop hasn't been seen yet, go through OAuth to create a session
if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
ctx.redirect(`/auth?shop=${shop}`);
} else {
await handleRequest(ctx);
}
});
router.get("/script_tag", (ctx) => {
handleRequest(ctx);
});
router.get("(/_next/static/.*)", handleRequest); // Static content is clear
router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
router.get("(.*)", verifyRequest(), handleRequest); // Everything else must have sessions
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
I am getting the error: document not defined.
What I've tried
I thought this is due to server side rendering, so I thought I could get around it by doing this:
if (typeof window !== "undefined") {
ReactDOM.render(<TestScriptTag />, document.getElementById('script-app'));
}
But still nothing renders and I get this when I inspect the shop page.
I've also tried changing the routing to this:
router.get("/script_tag", (ctx) => {
ctx.type = "module";
ctx.body = fs.createReadStream('./pages/script_tag.js')
});
But then I get an error about the import statement in script_tag.js - SyntaxError: Unexpected identifier '{'. import call expects exactly one argument.
I'm not sure what the proper way is to serve the javascript file I want to inject into the header. I feel like I'm missing something stupid. Please help!!
I am running my frontend code in react and doing server-side rendering using express.
Recently i did some changes and committed to my branch, mostly related to redux and updated my store.js file.
import universal from "react-universal-component";
import Loading from "./components/Loading";
import NotFound from "./components/NotFound";
// small function that allows page to be a string or a dynamic import function
// <UniversalComponent page={()=>{import('../../someFolder/Component.js')}}
// Its great for complex folder structures. You can leverage code completion
const determineHowToLoad = ({ page }) =>
typeof page !== "string" ? () => page() : import(`./${page}`);
const UniversalComponent = universal(determineHowToLoad, {
onError: error => {
throw error;
},
minDelay: 700,
loading: Loading,
error: NotFound
});
const loadComponent = file => universal(determineHowToLoad({ page: file }));
export { loadComponent, universal };
export default UniversalComponent;
Whenever i am hitting my site, after fetching all static files it gives this error:
"Uncaught (in promise) Error: export not found
at resolve (requireUniversalModule.js:90)"
I heard that Socket.io not worked properly in React Native, so I decided to use plain WebSocket instead.
I'm using node.js for implemeting WebSocket server, and it wasn't hard. With browsers, all of I tried worked, but with React native, none of success.
These are what I tried for implementing websocket server:
express-ws
ws
express-ws was just not worked without any error message. Just it saids failed to connect something.
So I changed the module to ws, and this module should be required both client and server, so I did. Server was worked, but when in the app with android on AVD, it saids:
Requiring unknown module "url".If you are sure the module is there,
try restarting the packager or running "npm install".
So I removed node_modules directory entirely and reinstall them, but same error shown up again.
I'm using node v6.2.2, and react-native-cli 1.0.0, react-native 0.33.0.
This is the server code with ws module(same as ws module readme):
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });
wss.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('Received: ' + msg);
});
socket.send('something');
});
This is client:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
const WebSocket = require('ws');
class wschat extends Component {
constructor() {
super();
}
componentDidMount() {
var socket = new WebSocket("ws://localhost:3000");
socket.on('open', () => {
socket.send('something');
});
socket.on('message', (data, flags) => {
console.log(data);
console.log(flags);
});
}
...
To avoid naming conflict, I was used WebSock instead WebSocket when requiring ws module, but it wasn't problem.
Is there a something that I missed? React Native doc has not much explanations, and it is hard to find working examples. Thanks for reading, and any advice will very appreciate it.
The latest react native supports websocket, so we don't have to depend on 3rd party websocket client library.
The following example is based on react native 0.45, and the project is generated by create-react-native-app.
import React, {Component} from 'react';
import {Text, View} from 'react-native';
export default class App extends React.Component {
constructor() {
super();
this.state = {
echo: ''
};
}
componentDidMount() {
var socket = new WebSocket('wss://echo.websocket.org/');
socket.onopen = () => socket.send(new Date().toGMTString());
socket.onmessage = ({data}) => {
console.log(data);
this.setState({echo: data});
setTimeout(() => {
socket.send(new Date().toGMTString());
}, 3000);
}
}
render() {
return (
<View>
<Text>websocket echo: {this.state.echo}</Text>
</View>
);
}
}
Install this package npm install websocket on your react native folder. The link to the relevant Github repo is this
import React, { useEffect } from 'react';
import { w3cwebsocket as W3CWebSocket } from "websocket";
import { Text} from 'react-native';
var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
function App() {
client.onopen = function() {
console.log('WebSocket Client Connected');
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
client.onclose = function() {
console.log('echo-protocol Client Closed');
};
client.onmessage = function(e) {
if (typeof e.data === 'string') {
console.log("Received: '" + e.data + "'");
}
};
return (
<Text>Practical Intro To WebSockets.</Text>
);
}
export default App;