Using AnyApi with React - java

I am trying to use AnyApi with my react app.
The request parameters are
IMDBid:string required
IMDB ID of the movie to return
GET https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}
I want to be able to type in the input box and return searches from the api in my container.
Im not getting any response from the Api, can anyone help
// importing useState so we can create states
import React, {useState, useEffect} from 'react';
// Imports style sheet for APP
import './App.css';
function App() {
// setting imdbID so we can use this as a value in the input box
const [imdbID,setimdbIDs] = useState('')
const [container,setContainer] = useState([])
useEffect(() =>{
fetchMe()
},[imdbID])
const fetchMe = () => {
fetch(`https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id={IMDBid}`, {
"method": "GET"
})
.then(response => {
return response.json();
})
.then(data => {
setContainer(data.d)
})
.catch(err => {
console.error(err);
});
}
//Every letter that is typed in the input box will then change imdbID to setimdbIDs
const onChangeHandler = (e) => {
setimdbIDs(e.target.value)
}
const submitHandler = e => {
e.preventDefault()
}
return (
<div className="App">
<form onSubmit={submitHandler}>
{/* input box value is imdbID calling onChangeHandler state*/}
<input type="text" value={imdbID} onChange={onChangeHandler}/>
{/* submit button */}
<button type="submite">SUBMIT</button>
</form>
{container.map((item) =>{
return (
<p>{item.l}</p>
)
})}
</div>
);
}
export default App;

You didnt provide the IMDBid in the url correctly
the template literal should be given like `string${expression}`
so your code would be
https://hydramovies.com/api-v2/%3Fsource=http:/hydramovies.com/api-v2/current-Movie-Data.csv&imdb_id=${IMDBid}

Related

am building the facebook gif post project, when i click on the gif it has to dispaly in the text area. But am stuck with type error post.map is nt fun

this is my main code, when I click on any gif am getting the data that is stored in the state but when I try to display the data in UI, am getting this below error.
`import { useState, useEffect } from "react"
import axios from 'axios';
import "./componentsStyles/GifContainerStyles.css"
import GifInText from './GifInText';
const GifPost = ({open, onClose}) => {
const [gifs, setGifs] = useState([])
const [gifId, setGifId] = useState([ ])
console.log("gifs:",gifs )
const fetchData = async () =>{
const response = await axios
.get("https://api.giphy.com/v1/gifs/trending",{
params: {
api_key: "Xoa3mXrWxKXw6lJscrKUTsbZsXLbGuGY"
}
}).catch((error) =>{
console.log("error at fetching data", error);
});
setGifs(response.data)
};
const getGifId = (id) => {
setGifId(id);
}
useEffect(() =>{
fetchData()
}, [ ]);
return (
<>
</div>
<div className='post-text'>
<form><textarea placeholder='Whats on your mind?'></textarea> </form>
{Object.keys(gifId).length === 0 ? null : <GifInText gifId={gifId}/> }
</div>
<div className='gif-container'>
<>
{Object.keys(gifs).length === 0 ? (<div>loading...</div>):
<div className='gif-section'>
{
gifs.data.map((items)=>{
return(
<a href="#" className='image-gifs' key=
{items.id}>
<img className="live-gifs" onClick=
{()=>getGifId(items.id)} src={items.images.fixed_height.url} alt="..."/>
</a>
)
})
}
</div>
}
</>
</div>
</>
)
}
export default GifPost;`
this is child component
`import { useState, useEffect } from "react";
import axios from "axios"
const GifInText = ({gifId}) => {
console.log("id:",gifId);
const [post, setPost] = useState([])
console.log("post:",post );
const fetchData = async () =>{
axios.get(`https://api.giphy.com/v1/gifs/${gifId}`,{
params: {
api_key: "Xoa3mXrWxKXw6lJscrKUTsbZsXLbGuGY",
gif_id: gifId
}
}).catch((error) =>{console.log("error at fetching gifID2", error);
}).then(response => {setPost(response.data) });}
useEffect(()=>{
fetchData()
}, [fetchData])
return (
<div>
{
post.data && post.data.map((items)=>{
return(
<a href="#" className='image-gifs' key={items.id}>
<img className="live-gifs" src={items.data.images} alt="..."/>
</a>
)
})
}
</div>
)
}
export default GifInText;`
Looks like you are trying to use map function on an object. You can only use map function directly on arrays.
In your console log, post is an object that contains more objects like data and meta.
Therefore, you need to make the following changes:
Firstly, change the state
const [post, setPost] = useState({});
And finally, use map on an object like this:
Object.values(post.data).length && Object.values(post.data).map((item)=>{
//use item here
})

Amazon Location map how to enable Route calculator, tracker map in react js project

I need your help to implement the AWS map, I have created the Arn for all the required map functionality but I don't know how to enable the search box and its functionality.
Map --> implemented
Place index --> need help
Route calculator --> need help
Geofence collection --> need help
Tracker --> need help
sample code for your reference:
import React, { useEffect, useState } from "react";
import { createRequestTransformer } from "amazon-location-helpers";
import { ICredentials } from "#aws-amplify/core";
import Amplify,{ Auth } from "aws-amplify";
import ReactMapGL, { NavigationControl, ViewportProps } from "react-map-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import amplifyConfig from "../aws-exports";
Amplify.configure(amplifyConfig);
// Replace with the name of the map that you created on the Amazon Location Service console: https://console.aws.amazon.com/location/maps/home
const mapName = "<MAP NAME>";
const Map = () => {
const [credentials, setCredentials] = useState<ICredentials>();
const [transformRequest, setRequestTransformer] = useState<Function>();
const [viewport, setViewport] = React.useState<Partial<ViewportProps>>({
longitude: -123.1187,
latitude: 49.2819,
zoom: 10,
});
useEffect(() => {
const fetchCredentials = async () => {
setCredentials(await Auth.currentUserCredentials());
};
fetchCredentials();
}, []);
// create a new transformRequest function whenever the credentials change
useEffect(() => {
const makeRequestTransformer = async () => {
if (credentials != null) {
const tr = await createRequestTransformer({
credentials,
region: amplifyConfig.aws_project_region,
});
// wrap the new value in an anonymous function to prevent React from recognizing it as a
// function and immediately calling it
setRequestTransformer(() => tr);
}
};
makeRequestTransformer();
}, [credentials]);
return (
<div>
{transformRequest ? (
<ReactMapGL
{...viewport}
width="100%"
height="100vh"
/** #ts-ignore */
transformRequest={transformRequest}
mapStyle={mapName}
onViewportChange={setViewport}
>
<div style={{ position: "absolute", left: 20, top: 20 }}>
<NavigationControl showCompass={false} />
</div>
</ReactMapGL>
) : (
<h1>Loading...</h1>
)}
</div>
);
};
export default Map;
reference image:
I don't know how to enable the tracker and place index functionality can I get anyone help on this. Thanks in advance.

How to make an alert Box that ask user if he wants to leave the page or not only angular?

I see every day that some app has a function that when you are on a page and you are filling, for example, a form and when you tried and click somewhere else for example in nav menu or even leave the page and you have unsafe change they ask the user if he wants to leave the page, I would really appreciate if someone can provide me an example of how can this be implemented in Angular, I am not sure if this is a front or backend job in backend I am working with java. Thanks a lot, each idea count :D.
You can use canDeactivate guard for every component,
First you have to add this service file "deactivate-guard.service.ts":
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class DeactivateGuardService implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
then you have to provide in the app module:
providers: [
DeactivateGuardService
]
now in the component you want to protect, add the function:
export class ExampleComponent {
loading: boolean = false;
#ViewChild('exampleForm') exampleForm: NgForm;
canDeactivate(): Observable<boolean> | boolean {
if (this.loading|| this.exampleForm.dirty) {
return this.confirmBox('Discard Unsaved Changes?');
}
return true;
}
confirmBox(message?: string): Observable<boolean> {
const confirmation = window.confirm(message || 'Are you sure?');
return of(confirmation);
};
}
Add the directive to the component in the routing module:
#NgModule({
imports: [
RouterModule.forRoot([
{
path: 'example',
canDeactivate: [DeactivateGuardService],
component: ExampleComponent
}
])
]
You can use the canDeactivate guard to check a page leave and display the warning message you wish to display something like this
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
#Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
include set the can activate guard to the route like this
{ path: 'sample-path', component: SampleComponent, canDeactivate: [CanDeactivateGuard] },
and the canDeactivate method to the component
canDeactivate() {
if (this.formIsIncomplete > 0) {
let result: boolean = window.confirm("You have unsaved Changes");
return result;
}
return true;
}
it may helpful for you to make alert
https://stackblitz.com/edit/angular-confirmation-dialog

ReactJS/Javascript: map function and rendering

The Graph component is getting data (verified in console) but for some reason the page is still blank. I am not quit sure I understand how the map function works. This is the last piece I need to figure out to render this graph but for whatever reason I can't seem to get any graphics on the screen. The state of nodes in the console is:
{data: {action: [{action: "Changed", timestamp: 1499348050,…},…]}}
data:{action: [{action: "Changed", timestamp: 1499348050,…},…]}
action:[{action: "User Assist Changed", timestamp: 1499348050,…},…]
Graph Component:
import React, {Component} from 'react';
import * as d3 from "d3";
import {graphql} from 'react-apollo';
import getObjectsQuery from './Queries';
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = { startTime:this.props.startTime,
endTime:this.props.endTime,
nodes:this.props.getObjectsQuery
}
//console.log('graph data:', this.props.data)
}
componentDidMount() {
console.log('nodes:', this.props.data)
this.force = d3.forceSimulation(this.props.data)
.force("charge",
d3.forceManyBody()
.strength(this.props.forceStrength)
)
.force("x", d3.forceX(this.props.width / 2))
.force("y", d3.forceY(this.props.height / 2));
this.force.on('tick', () => this.setState({nodes: this.props.data}));
console.log('setState:', this.props.data);
}
componentWillUnmount() {
this.force.stop();
}
render() {
// console.log('graph datas:', this.props.data)
return (
<svg width={this.props.width} height={this.props.height}>
{Object.keys(this.props.data).map((action, index) =>(
<circle r={action.action} cx={action.second} cy={action.obj} fill="red" key={index}/>
))}
</svg>
);
}//render
}//Component
export default graphql(getObjectsQuery,
{ options: (ownProps) => {
console.log(ownProps.startTime);
return ({ second: { startTime: ownProps.startTime,
endTime: ownProps.endTime
} })
} } )(Graph);
Graph.defaultProps = {
width: 300,
height: 300,
forceStrength: -10
};
If this.props.data.action is an array then it can be used directly in map:
{this.props.data.action.map((action,
but this.props.data.action (and even this.props.data?) can be undefined on start, first render
use some conditions in render to prevent errors, f.e.
{!this.props.data.loading && this.props.data.action.map((action,
Check if loading is present ... structure of props passed into component can be mapped differently by fn defined in config props property in graphql() (f.e. in case of conflict props names). Search for examples.

How to use a copy form windows inside web application just like the image copy inside google gmail

Inside gmail you can use the paste option to paste an image directly form windows clipboard. My obvious question is: How to do this.
I found techniques to copy text with use of flash code but this is poorly what I am looking for. The idea is that I copy an image or text inside windows and then paste it inside an simple text editor from ticked system.
It has to work fully automatic so it sees if the data is text and shut be inside tags and if it is an image it has to be inside the <img> tag. Like this <img src="rawimagedata" title="filename.jpg" />
Someone a tip or better a script example. No matter if you use flash or java if it works it works for me.
Thank you in advance.
You have to encode it in Java
byte[] byteArray = new byte[102400];
base64String = Base64.encode(byteArray);
byteArray is the picture and with the Base64.encode function you get the string you have to enter below
more infos see: https://stackoverflow.com/a/10226133/1667829
and then you can show it like that:
<div>
<p>Taken from wikpedia</p>
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div>
http://jsfiddle.net/hpP45/
I found a way to get the image it is only working for Google chrome. I am busy working on a version that works on Firefox as well.
With inspiration form: http://strd6.com/2011/09/html5-javascript-pasting-image-data-in-chrome/
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="jquery.js" type="text/javascript"></script>
<script>
// Created by STRd6
// MIT License
// jquery.paste_image_reader.js
(function() {
(function($) {
var defaults;
$.event.fix = (function(originalFix) {
return function(event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
return $.fn.pasteImageReader = function(options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function() {
var $this, element;
element = this;
$this = $(this);
return $this.bind('paste', function(event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
return Array.prototype.forEach.call(clipboardData.types, function(type, i) {
var file, reader;
if (found) {
return;
}
if (type.match(options.matchType) || clipboardData.items[i].type.match(options.matchType)) {
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function(evt) {
return options.callback.call(element, {
dataURL: evt.target.result,
event: evt,
file: file,
name: file.name
});
};
reader.readAsDataURL(file);
return found = true;
}
});
});
});
};
})(jQuery);
}).call(this);
jQuery("html").pasteImageReader(function(results) {
var dataURL, filename;
filename = results.filename, dataURL = results.dataURL;
jQuery('#deze').html('<img src="' + dataURL + '" />');
});
</script>
<style>
#deze{
height:400px;
width:400px;
border:2px solid red;
}
</style>
</head>
<body>
<div id="deze">testdiv</div>
</body>
</html>
note:
In this example the creator override the $ sing and you can not use jquery anymore like this: $('#deze')

Categories

Resources