React Highcharts error - reactjs

Looking for some help with the react wrapper for highcharts it seems to be throwing this error every-time I go to start the dev server for my application.
Error message Highcharts
With that Said I am sure that It is an issue with my code and not the Highcharts react wrapper. I am looking for some help to remedy this error. Thank you.
I am using another node wrapper for the Tradier API for market data and want to compare multiple tickers historically like the chart that is provided in Highchart's Demo. (Found here)
I Know I need to iterate through the returned JSON from Tradier- which
returns an array of objects for a particular ticker symbol.
{ day:
[ { date: '2017-01-03',
open: 115.8,
high: 116.33,
low: 114.76,
close: 116.15,
volume: 28781865 }...
]
I have Gone ahead and uploaded the app to a github repository. The code for the Highstock component I am trying to add in react is below, along with the github links for the used packages.
import React from 'react'
import Highcharts from 'highcharts/highstock'
import HighchartsReact from 'highcharts-react-official'
import Tradier from 'tradier-client';
class HighchartSector extends React.Component {
constructor(props){
super(props)
this.state = {
store: [],
openPrice: []
}
}
componentDidMount() {
const tradier = new Tradier('7svYXqoAjts9fGptLU7mtKo4Z4Oa', 'sandbox');
tradier.historical('LADR')
.then(history => history.day.map( result =>(
{
open: `${result.open}`,
})))
.then(newData => this.setState({openPrice: newData, store: newData}))
.catch(error => alert(error))
}
render() {
const { openPrice } = this.state;
const options = {
title: {
text: 'My stock chart'
},
series: [{
data: openPrice
}]
}
return (
<HighchartsReact
highcharts={Highcharts}
constructorType={'stockChart'}
options={options}
/>
)
}
}
export default HighchartSector
My Git Repo: HERE
Tradier vporta wrapper: HERE
Highcharts-Official React Wrapper: HERE

Related

Adding cloudinary playList widget in React

I have React app running videos from cloudinary. I have managed to edit Video tag but want to also add playlistWidget. Where does this fit into code/Video tag? The example provided on cloudinary is for javascript not React.
https://cloudinary.com/documentation/video_player_customization
Here is ex of my component with cloudinary player.
import React from "react";
import axios from "axios";
import "./VideoPlayer.css"
import { inDev } from "../API";
const devAPI = "http://localhost:8081/api/";
const baseAPI = "api/";
import {Image, Video, Transformation, CloudinaryContext} from 'cloudinary-react';
class Player extends React.Component {
constructor(props) {
super(props);
this.state = {
WelcomeVideo:"https://res.cloudinary.com/Name/video/upload/v1594509086/ab7qqxjexpwfv4j7kzj2x.mp4",
Logo:"https://res.cloudinary.com/example/image/upload/v1599423081/Logo1.png",
};
}
render() {
return ( <div style={{textAlign: "center"}}>
<h1 style={{fontSize:"60px"}}>Video of Week!</h1>
<Video
id="example-player"
cloudName="demo"
src={this.state.WelcomeVideo}
publicId="cat"
controls
autoPlay="true"
preload= "auto"
class="cld-video-player"
poster={this.state.Logo}
width= "400"
height="320"
fallback="Cannot display video"
/>
</div>
);
}
}
export default Player;
Updated recommendations per cloudinary https://cloudinary.com/documentation/video_player_playlists_recommendations#:~:text=playlist%20widget%20%2D%20A%20scrollable%20list,a%20full%20screen%20web%20browser.
import React, { Component } from "react";
import { Cloudinary } from "cloudinary-core";
import "cloudinary-video-player/dist/cld-video-player";
class PlayerCloud extends Component {
componentDidMount() {
// Setting video sources:
var source1 = { publicId: 'elephants', info: { title: 'My main movie',
subtitle: 'Something to know about the main movie' } }
var source2 = { publicId: 'cat', info: { title: 'Another great video',
subtitle: 'A great subtitle',
description: 'An interesting description of this video....' } }
var source3 = { publicId: 'dog', info: { title: 'Another interesting video1',
subtitle: 'Subtitle for video3', description: 'An interesting description of this video....' } }
// Specifying the recommendations for source1 as a fixed array of sources:
source1.recommendations = [source2, source3]
const cld = new Cloudinary({ cloud_name: "demo", secure: true });
const videoName = "elephants";
var demoplayer = cld.videoPlayer("some-video", {
publicId: source1.publicId,
controls: true,
preload: "auto",
muted: true,
autoplay: true,
width: 300,
autoShowRecommendations:true
});
}
render() {
return (
<div>
<video
id="some-video"
/>
</div>
);
}
}
export default PlayerCloud;
See this Codesandbox showing how to bind the video player code to a video tag. Once you are running a video player instead of an HTML 5 video tag, you can add functionality like the playList Widget
https://codesandbox.io/s/em2g0
https://cloudinary.com/documentation/video_player_playlists_recommendations#creating_a_playlist
The video player requires CSS that is in the index.html as well as binding functionality to a video tag.
Here's another react Sandbox which just shows a short video in the video player. [https://codesandbox.io/s/react-cld-video-player-v2-yfgxi?file=/src/VideoPlayerTest.js][1]
You can find more information about video player options and style here: https://cloudinary.com/documentation/cloudinary_video_player

Using ReactJs to fetch data from an API but getting completely blank page with no errors

Guys Kindly i need your help. I am trying to fetch data from an Api and display it in the dom. I can see the data in the console but when i try to return data it shows a blank page and no errors. Below is my code.
App.js file
import React from "react";
import "./App.css";
import Movieapp from "./Movieapp";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
title: [],
date: [],
image: []
};
}
componentDidMount() {
fetch(`https://yts.mx/api/v2/list_movies.json?quality=3D`)
.then(res => res.json())
.then(data => {
console.log(data.data);
this.setState = {
title: data.data.movies[0].title,
date: data.data.movies[0].date_uploaded,
image: data.data.movies[0].background_image
};
});
}
render() {
return (
<div className="App">
<Movieapp
title={this.state.title}
date={this.state.date}
image={this.state.image}
/>
</div>
);
}
}
export default App;
Movieapp.js file
import React from "react";
const Movieapp = props => {
return (
<div>
<h1>{props.title}</h1>
<h1>{props.date}</h1>
<div>{props.image}</div>
</div>
);
};
export default Movieapp;
this.setState is a function, not a property. You have to use it properly:
this.setState({
title: data.data.movies[0].title,
date: data.data.movies[0].date_uploaded,
image: data.data.movies[0].background_image
});
Also, even though I guess you are just trying things our, there are few things to be aware of:
movies[0] can be undefined
You are getting multiple movies but showing only one. It's probably better to just save the whole data array in the state and iterate over the results in the render method

ReactJS FullCalendar won't load events into calendar

Im grabbing the events dynamically from my backend API however when I make the call compoentWillMount() its as if the calendar is loading first and not getting the events so its not loading/displaying the events on the calendar. I keep looking through the docs and trying different solutions and cant get anything to succeed. My components code:
import React from "react";
import Tooltip from "tooltip.js";
import moment from 'moment';
import ErrorBoundary from "../Utils/ErrorBoundary";
import FullCalendar from "#fullcalendar/react";
import dayGridPlugin from "#fullcalendar/daygrid";
import interactionPlugin from "#fullcalendar/interaction";
import "#fullcalendar/core/main.css";
import "#fullcalendar/daygrid/main.css";
class ChoreCalendar extends React.Component {
constructor(props) {
super(props);
this.state = {
chores: [],
events: []
};
}
componentWillMount() {
fetch('http://localhost:8080/api/chores')
.then(res => res.json())
.then((data) => {
this.setState({ chores: data })
data.data.forEach(chore => {
this.state.events.push({
title: chore.title,
date: moment(chore.dueDate).format("YYYY-MM-DD"),
color: "green",
textColor: "white"
})
});
})
.catch(console.log)
}
eventRender(info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.title,
placement: "top",
trigger: "click",
container: "body"
});
}
render() {
return (
<div className="ibox">
<div className="ibox-content">
<ErrorBoundary>
<FullCalendar
id="fullCalendar"
defaultView="dayGridMonth"
plugins={[dayGridPlugin, interactionPlugin]}
events={this.state.events}
eventRender={this.eventRender}
schedulerLicenseKey="GPL-My-Project-Is-Open-Source"
/>
</ErrorBoundary>
</div>
</div>
);
}
}
export default ChoreCalendar;
All I'm currently trying to do is dynamically grab the events and then load them into the calendar and have them show.
Add initialEvent prop in FullCalender Tag and assign it some state with initial values.

How to integrate Phaser into React

I've got a React application created with create-react-app and I'm trying to integrate Phaser 3 as well. I followed this guide to get started. I've got the canvas rendering the text but loading images in the preload does not seem to be working. I get the default failed to load texture image displayed.
import ExampleScene from "./scenes/ExampleScene";
import * as React from "react";
export default class Game extends React.Component {
componentDidMount() {
const config = {
type: Phaser.AUTO,
parent: "phaser-example",
width: 800,
height: 600,
scene: [ExampleScene]
};
new Phaser.Game(config);
}
shouldComponentUpdate() {
return false;
}
render() {
return <div id="phaser-game" />;
}
}
ExampleScene:
import Phaser from "phaser";
export default class ExampleScene extends Phaser.Scene {
preload() {
this.load.image("logo", "assets/logo.png");
}
create() {
const text = this.add.text(250, 250, "Phaser", {
backgroundColor: "white",
color: "blue",
fontSize: 48
});
text.setInteractive({ useHandCursor: true });
this.add.image(400, 300, "logo");
text.on("pointerup", () => {
console.log("Hello!");
//store.dispatch({ type: ACTION_TYPE });
});
}
}
The idea is to create a visualization with flowers growing based on a simple gene engine. So Phaser would get instructions from the Store about the current state.
I'm guess this has something to do with the way Phaser loads and there's a conflict with how React updates. I'm preventing the component from updating as I only need the game to receive instructions by listening to the store
I've already looked at this SO answer and the accompanying wrapper, but it is outdated.
How can I get Phaser to load images when in a Create-React-App?
CodeSandbox: https://codesandbox.io/s/github/nodes777/react-punnett/tree/phaser-game
Repo: https://github.com/nodes777/react-punnett/tree/phaser-game
Other option is using WebComponents to be able to integrate Phaser with any other framework (React, Angular, VueJS, etc), check this npm package: https://www.npmjs.com/package/#ion-phaser/core
Also, you can use the React wrapper of that library to use Phaser with React components easily, so you don't need to manipulate WebComponents directly, example:
import React from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '#ion-phaser/react'
const game = {
width: "100%",
height: "100%",
type: Phaser.AUTO,
scene: {
init: function() {
this.cameras.main.setBackgroundColor('#24252A')
},
create: function() {
this.helloWorld = this.add.text(
this.cameras.main.centerX,
this.cameras.main.centerY,
"Hello World", {
font: "40px Arial",
fill: "#ffffff"
}
);
this.helloWorld.setOrigin(0.5);
},
update: function() {
this.helloWorld.angle += 1;
}
}
}
const App = () => {
return (
<IonPhaser game={game} />
)
}
export default App;
Fore more details check the repo: https://github.com/proyecto26/ion-phaser/tree/master/react
A year ago I was here looking for the answer myself. Here's pattern which should work.
import Phaser from "phaser"
import React, { useEffect, useState } from "react"
/** #tutorial I made this! This answers how you get your image. */
import logoImage from "./path-to-logo.png"
/** #tutorial I made this! Use a functional React component and `useEffect` hook.*/
export const Phaser3GameComponent = ({ someState }) => {
// Optional: useful to delay appearance and avoid canvas flicker.
const [isReady, setReady] = useState(false)
// Just an example... do what you do here.
const dataService = (changedState) => {
// I'm not sure how to use stores, but you'll know better what to do here.
store.dispatch(
{
...someState,
...changedState,
},
{ type: ACTION_TYPE }
)
}
// This is where the fun starts.
useEffect(() => {
const config = {
callbacks: {
preBoot: game => {
// A good way to get data state into the game.
game.registry.merge(someState)
// This is a good way to catch when that data changes.
game.registry.events.on("changedata", (par, key, val, prevVal) => {
// Simply call whatever functions you want outside.
dataService({ [key]: val })
})
},
},
type: Phaser.AUTO,
parent: "phaser-example",
width: 800,
height: 600,
scene: [ExampleScene],
}
let game = new Phaser.Game(config)
// Triggered when game is fully READY.
game.events.on("READY", setReady)
// If you don't do this, you get duplicates of the canvas piling up.
return () => {
setReady(false)
game.destroy(true)
}
}, []) // Keep the empty array otherwise the game will restart on every render.
return (
<div id="phaser-example" className={isReady ? "visible" : "invisible"} />
)
}
export default class ExampleScene extends Phaser.Scene {
preload() {
this.load.image("logo", logoImage)
}
create() {
// You made this!
const text = this.add.text(250, 250, "Phaser")
text.setInteractive({ useHandCursor: true })
this.add.image(400, 300, "logo")
/** #tutorial I made this! */
// Get all that lovely dataState into your scene,
let { clickCount } = this.registry.getAll()
text.on("pointerup", () => {
// This will trigger the "changedata" event handled by the component.
this.registry.merge({ clickCount: clickCount++ })
})
// This will trigger the scene as now being ready.
this.game.events.emit("READY", true)
}
}
I started from scratch and created my own boilerplate from the phaser 3 template. I wrote about the specific steps to add React to the Phaser 3 template here.
It seems like you could eject from Create-React-App and add in Phaser 3 from there, but the warnings not to eject turned me away from that solution.
In my case I use the following component and it works fine:
import Phaser from 'phaser';
import * as React from 'react';
import { HTML_DIV_ID, gameConfig } from './gameConfig';
export const GameWrapper = () => {
const [game, setGame] = React.useState<Phaser.Game>();
React.useEffect(() => {
const _game = new Phaser.Game(gameConfig());
setGame(_game);
return (): void => {
_game.destroy(true);
setGame(undefined);
};
}, []);
return (
<>
<div id={HTML_DIV_ID} />
</>
);
};
With create-react-app and React.StrictMode:
Also I deleted React.StrictMode (default option with create-react-app) because it mounts
and unmounts all components so I had unexpected behavior with phaser
sometimes
You can use react hook for the code above as:
// usePhaser.js
export function userPhaser(config) {
const [game, setGame] = React.useState();
React.useEffect(() => {
const _game = new Phaser.Game(config);
setGame(_game);
return (): void => {
_game.destroy(true);
setGame(undefined);
};
}, []);
return game;
}
You need to put images inside the folder public!
For me, I see the best practice to use both of them properly is to create phaser project separately and host it separately using firebase or whatever hosting service you prefer, and then take the link and put it in an iframe tag inside react.
in this way you can manage them efficiently and you can manipulate react website in more comfortable way especially the mobile width compatibility.

React jest testing. Cannot read property 'maps' of undefined with google js api

Hi guys I've setup the Google Maps JavaScript API and its working all fine, but my tests all fail now with the error
TypeError: Cannot read property 'maps' of undefined.
Here is what my component looks like
import React, { Component } from 'react'
import { connect } from 'react-redux'
import List from './List'
import { fetchPlaces } from '../../store/actions/places'
const google = window.google
export class Places extends Component {
componentDidMount() {
const pyrmont = { lat: -33.866, lng: 151.196 };
const service = new google.maps.places.PlacesService(document.getElementById('map'))
// this.props.fetchPlaces('fitzroy')
const request = {
location: pyrmont,
radius: 500, type:
['restaurant'],
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
fields: ['name', 'rating', 'formatted_phone_number', 'geometry']
};
service.nearbySearch(request, callback);
function callback(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(place)
}
}
}
....rest of component
Here's what my test looks like
import React from 'react'
import { render, renderIntoDocument } from 'react-testing-library'
import 'jest-dom/extend-expect'
import { Places } from '../../Places/Places'
const baseProps = {
fetchPlaces: jest.fn(),
};
test('it shows a loading message when places are being loaded on mount', () => {
const { container } = render(<Places loading={true} places={[]} {...baseProps} />)
expect(container).toHaveTextContent('Loading')
});
First line of the error stack is
"at Places.componentDidMount (src/components/Places/Places.js:13:34)"
EDIT: I've setup a mock of the google api in my test file and if I console.log the google object its no longer undefined but I still get the same error in my test.
const setupGoogleMock = () => {
const google = {
maps: {
places: {
AutocompleteService: () => { },
PlacesServiceStatus: {
INVALID_REQUEST: 'INVALID_REQUEST',
NOT_FOUND: 'NOT_FOUND',
OK: 'OK',
OVER_QUERY_LIMIT: 'OVER_QUERY_LIMIT',
REQUEST_DENIED: 'REQUEST_DENIED',
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
ZERO_RESULTS: 'ZERO_RESULTS',
},
},
Geocoder: () => { },
GeocoderStatus: {
ERROR: 'ERROR',
INVALID_REQUEST: 'INVALID_REQUEST',
OK: 'OK',
OVER_QUERY_LIMIT: 'OVER_QUERY_LIMIT',
REQUEST_DENIED: 'REQUEST_DENIED',
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
ZERO_RESULTS: 'ZERO_RESULTS',
},
},
};
global.window.google = google;
};
beforeAll(() => {
setupGoogleMock();
});
I ran ran into a similar issue today, with an error of: TypeError: window.google.maps.places.AutocompleteService is not a constructor
I found a fix from CRA issue #955 - here
Basically you change the AutoCompleteService line to Autocomplete: class {}. Keep the rest of that mock file the same.
Although, the test that I have (which is now passing) is just the basic CRA initial test of 'it renders without crashing' but it should work out for you as well
Some modules might not work well inside a testing environment, or may not be as essential to the test itself. Mocking out these modules with dummy replacements can make it easier to write tests for your own code. Click Here For Detail
import MockedMap from "./map";
jest.mock("./map", () => {
return function DummyMap(props) {
return (
<div data-testid="map">
{props.center.lat}:{props.center.long}
</div>
);
};
});

Resources