https://github.com/kriasoft/react-starter-kit
I have a backend API server running and I am looking for a frontend framework. Then I came across this react-starter-kit that seems to be a good candidate.
My understanding is that I am dealing with react components one at a time. and I can put the all code logic such as API calls, DOM element changes....etc in componentDidMount() so there will be interaction between DOM and the logic. (am I right?)
import React, { PropTypes } from 'react'; // eslint-disable-line no-unused-vars
import styles from './ContactPage.less'; // eslint-disable-line no-unused-vars
import withStyles from '../../decorators/withStyles'; // eslint-disable-line no-unused-vars
#withStyles(styles)
class ContactPage {
static contextTypes = {
onSetTitle: PropTypes.func.isRequired
};
render() {
let title = 'Contact Us';
this.context.onSetTitle(title);
return (
<div className="ContactPage">
<div className="ContactPage-container">
<h1>{title}</h1>
<p>...</p>
</div>
</div>
);
}
}
export default ContactPage;
This is the original code of the react component I am trying to hack. I tried to include "request" module so that I can make http requests.
var request = require('request'); // for backend API calls
componentDidMount() {
request('https://www.google.com')
}
It didn't work. So what I am doing wrong here? Thanks.
The error message is very long, started with the following message.
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /Users/ssmlee04/Desktop/react-starter-kit/node_modules/request/lib
# ./~/request/lib/har.js 3:9-22
Request.js is a lib for Node. It is not meant to be used in the browser. That is why you are seeing the error module fs not found. fs is the file system module of node js.
Since you are already using ES6 I suggest to use fetch (https://fetch.spec.whatwg.org/) to make request to the remote server. It is already supported by chrome and firefox. To have compatibility with older browser you can use fetch polyfill from github. Here it is the link to the repo https://github.com/github/fetch.
Related
I am building a react app (this part might be inconsequential) and have a server cloud function built:
exports.myFunction = functions.https.onCall(async (data, context) => {
...
}
I know that calling this in my client would normally consist of calling
firebase.functions().httpsCallable('myFunction');
And I have tried this in a separate project, and it works. However, that was using a script tag to import the functions module in my index.html:
<script src="/__/firebase/7.7.9/firebase-functions.js"></script>
but in my current project, my modules are imported in my firebase.js source:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: ...
...
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
I wasn't able to find any example code for importing functions this way, and everything I have tried has failed.
How can I import functions so that I can invoke the above method? Even better, how could I figure this out on my own? (I have been relying on example code so far). I assume that these are referencing the NPM packages I have npm install'ed (or in my case, yarn add'ed), but I don't immediately see where the code is actually being referenced so I can work this out on my own.
As far what I have understood from you question it is regarding how can firebase cloud function module be imported while using a react app which is calling a HTTPS callable function at the client side.You can use any library or built-in command of your environment to call a HTTPS function.
I would recommend you to try the following to your imports and see if that works.
import { getFunctions, httpsCallable } from "firebase/functions";
OR
import * as functions from 'firebase-functions'; import React from 'react'; import { renderToString } from 'react-dom/server'; import App from './src/App';
Check the below for similar implementation examples to better understand this and implement according to your requirements.
How to call Firebase function from within react component
Call Firebase HTTPS callable function in react
Implement callable function in react app
Firebase callable function CORS
I have a project which is on react but files are not .js instead they are .tsx and I am trying to use stripe library but keep getting error.
I have tried few different libraries which help setting up stripe but I am keep getting stuck on this errr.
Please help or direct me to correct library which help me setup stripe.
my codes are
import ReactDOM from "react-dom";
import StripeCheckout from 'react-stripe-checkout';
import axios from "axios";
function handleToken(token, addresses) {
console.log(token, addresses);
}
export default function Webinar() {
return (
<div className="container">
<StripeCheckout stripeKey = "mykey"
token={handleToken}
name="Tesla Roadster"
billingAddress
shippingAddress
/>
</div>
);
}
The problem is saying that your Typescript repo is now strict mode enabled which forces you specify the typing. If you wish to keep it silent, you can simply switch it to false in tsconfig.json:
{
"compilerOptions": {
"strict": false,
// ...
}
}
Change your function handleToken to be a variable with has the same type of your component prop as following:
const handleToken: StripeCheckout['props']['token'] = (token) => {
// You can receive hint from token type here
}
I use mapbox-gl, specifically mapbox-gl-leaflet, in React to create a map:
import Leaflet from 'leaflet'
import 'mapbox-gl/dist/mapbox-gl.css'
import {} from 'mapbox-gl-leaflet'
import 'leaflet/dist/leaflet.css'
const Map = () => {
const map = useRef(null)
useEffect(() => {
Leaflet.mapboxGL({
accessToken: token,
style: 'mapbox://styles/mapbox/outdoors-v11',
}).addTo(map.current)
})
}
In the test it already fails when I try to mount <Map /> with this error:
Failed to initialize WebGL.
There are also two other Error messages:
Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package) ...
This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.
But as you can see I import the CSS file. I think the problem is that in Jest there is no WebGL available. I also installed the canvas npm package, but it didn't seem to help.
Is it possible to somehow mock WebGL? I already tried it with jest-canvas-mock. I importet it in the test file: import {} from 'jest-canvas-mock'. But I still get the Error: Not implemented: HTMLCanvasElement.prototype.getContext ... error.
I'm trying to use lazy loading for my create-react-app with react#16.5.2 and I did this :
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
const Header = React.lazy(() => import('./_header'));
class SomeFile extends Component {
render() {
return (
<BrowserRouter>
<React.Fragment>
<Header />
</React.Fragment>
</BrowserRouter>
);
}
}
export default SomeFile;
Do you know why this error occurs ? is it because of my react version ? based on this everything seems fine!
Edit
What does this mean? based on reactjs.org :
Note:
React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we recommend Loadable Components. It has a nice guide for bundle splitting with server-side rendering.
React.lazy is only available from v16.6.0 https://reactjs.org/blog/2018/10/23/react-v-16-6.html
In your comand line interface, try updating React using the following command:
npm i react#latest
Restart Development Server, if you still face issue try the above steps:
Search for REACT_EDITOR on the Readme.md file, and insert =atom in front of it, like as follow:
REACT_EDITOR=atom
Then, save, restart the development server. It should work now
Does axios-mock-adapter only work on requests made with axios?
I have written a component that POSTs to an API (using vanilla XHR, not axios). I'm testing it in Storybook and want to intercept those POST requests since the endpoint doesn't exist yet:
import React from "react"
import { storiesOf } from "#kadira/storybook"
import MyComponent from "./MyComponent"
import axios from "axios"
import MockAdapter from "axios-mock-adapter"
var mock = new MockAdapter(axios)
storiesOf("My Component", module).addWithInfo(
"Simulator",
() => {
mock.onPost().reply(500)
return <MyComponent />
},
{}
)
My component still is trying to hit the API endpoint and I am getting a 404 response - not the expected 500 response.
Does axios-mock-adapter only work on requests made with axios?
Does the mock call have to be inside MyComponent?
Thanks.
xhr-mock should work for local testing where you probably don't want to make requests across the internet.
Outside of testing, if you are waiting on the real endpoints to be built you could use Mock/it (https://mockit.io) in development. You can claim your own dedicated subdomain and swap it out later for the real one. Disclaimer: this is a side project I recently released and would love any feedback on it!
You can use xhr-mock instead of axios-mock-adapter.
Utility for mocking XMLHttpRequest.
Great for testing. Great for prototyping while your backend is still being built.
Works in NodeJS and in the browser. Is compatible with Axios, jQuery, Superagent >and probably every other library built on XMLHttpRequest
import mock from 'xhr-mock';
storiesOf("My Component", module).addWithInfo("Simulator",
() => {
mock.post('', {
status: 500,
body: '{}'
});
return <MyComponent />
},
{}
)
Additionaly you need to add jquery script in preview-head.html file in storybook
1) https://www.npmjs.com/package/xhr-mock
I've started using json-server to intercept API calls. You have to start it in one tab, and start storybook in another, but it is pretty cool.
You can use fetchMock npm module. All XHR call will be mocked with data you provide.
Storybook configuration:
import React from 'react';
import Messages from '../components/messagesList';
import fetchMock from "fetch-mock";
import MESSAGES from './data/messages';
fetchMock.get('/messages', MESSAGES);
export default {
title: 'Messages',
component: Messages
};
export const ToStorybook = () => <Messages />;
ToStorybook.story = {
name: 'Messages list',
};
The complete tutorial how to do it is on YouTube
You can use storybook-addon-mock to mock any fetch or XHR request using the addon panel.
This package supports
Modify response from the panel and test on the fly.
Modify the status code to verify the error response.
Add a delay time to experience the loading state.