In my React project, I am taking as inputs "Lat" and "Long" from user .I'm using geolocation to get user location. These changes are working fine with all browsers but not Chrome.
By using VPN and changing my IP, Chrome started working but this IP number is not real since my location changed.
Please help me to solve this issue or give me suggestion to try another package or Direction
thanks :)
import { useEffect } from "react";
export default function LocationInput({ Location, setLocation }) {
useEffect(() => {
if ("geolocation" in navigator) {
console.log("Available");
} else {
console.log("Not Available");
}
}, []);
const Handellocation = () => {
navigator.geolocation.getCurrentPosition(function (position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
setLocation({
lat: position.coords.latitude,
long: position.coords.longitude,
ButtonText: "find you !",
ButtonColor: "#50C878",
});
});
};
return (
<div>
<p className="text">get locatin</p>
<div className="location">
<button
onClick={Handellocation}
style={{ backgroundColor: Location.ButtonColor }}
>
{Location.ButtonText}
</button>
</div>
</div>
);
}
I think this happens because of some countries being blacklisted for certain Google APIs, hence chrome wont support this. You need to work around with a different data-source ( DB/API/pollyfill)
Reference to the blacklisting: https://cloud.google.com/maps-platform/terms/maps-prohibited-territories
Related
I've made a netflix clone using React.js, firebase, and have used TMDB api for movie database.
I've also used react-youtube and movie-trailer npm.
So it has this feature that every time I click on any movie poster, it's trailer must be played.
But for most of the movies, trailer doesn't shows up.
This is the error that I face -
movie-trailer: No TMDB Movie found with the current search terms, try searching https://www.themoviedb.org/search?query=Luis%20Miguel%3A%20The%20Series
TypeError: Failed to construct 'URL': Invalid URL
at Row.js:37
'This is the screenshot of errors I am facing on clicking maximum of movies'
I'm sharing the link of my github repo and deployed website as well for reference -
github - https://github.com/IshitaSharma3101/netflix-clone
website - https://netflix-clone-afb8b.web.app/
Row component code-
import React, { useState, useEffect } from "react";
import YouTube from "react-youtube";
import axios from "./axios";
import "./Row.css";
import movieTrailer from "movie-trailer"
const base_url = "https://image.tmdb.org/t/p/original/";
function Row({ title, fetchURL, isLargeRow }) {
const [movies, setMovies] = useState([]);
const [trailerURL, setTrailerURL] = useState("");
useEffect(() => {
async function fetchData() {
const request = await axios.get(fetchURL);
console.log(request.data.results);
setMovies(request.data.results);
return request;
}
fetchData();
}, [fetchURL]);
const opts = {
height: "390",
width: "100%",
playerVars: {
autoplay: 1,
},
};
const handleClick = (movie) => {
if (trailerURL) {
setTrailerURL("");
} else {
movieTrailer(movie?.name || movie?.title || movie?.original_title || "")
.then((url) => {
const urlParams = new URLSearchParams(new URL(url).search);
setTrailerURL(urlParams.get("v"));
})
.catch((error) => console.log(error));
}
};
return (
<div className='row'>
<h2>{title}</h2>
<div className='row__posters'>
{movies.map((movie) => (
<img
key={movie.id}
onClick={() => handleClick(movie)}
className={`row__poster ${isLargeRow && "row__posterLarge"}`}
src={`${base_url}${
isLargeRow ? movie.poster_path : movie.backdrop_path
}`}
alt={movie.name}
/>
))}
</div>
{trailerURL && <YouTube videoId={trailerURL} opts={opts} />}
</div>
);
}
export default Row;
I'm sure you are following the Clever Qazi tutorial as I'm doing. I think there is basically no solution for this problem. I also try to get the trailer of the movies by the ID that TMDB gives for every film but this method definitely doesn't work for mine. My conclusion is that movie-trailer is not working for certain kind of film or series...
You can prove yourself my conlclusion by typing on a terminal npx movie-trailer Cobra Kai
which is the command that allow you to use this package. Cobra Kai is a well know series but this "tool" doesn't find any trailer for it.
Use this instead.
movieTrailer(null ,{ tmdbId: movie.id })
.then((url)=>{
console.log("url is "+url);
const urlParams=new URLSearchParams(new URL(url).search);
console.log("urlParamsn"+urlParams);
setTrailerUrl(urlParams.get("v"));
})
.catch((error)=> console.log(error));
}
}
With this you can search for the movie with the tmdb id.
This error is coming becouse TMDB has not added ids for some videos if you want to play all video you just need need to change the genres of the Netflix Original Video from the path in request.js folder where you wrote your path becouse Netflix originals Videos has not linked with ids on TMDB.
I have built a chat using Firebase and ReactJS. I mainly followed their Firebase's web codelab at https://firebase.google.com/codelabs/firebase-web#1. However, I have gotten stuck on the image uploading functionality. Since I am using ReactJS, I have had to modify their plain JS code to match mine. I am able to save a message with a "loading" image url in Firestore, then, I successfully save the image that I want to ultimately show in the chat in Firebase Storage, and finally then I successfully retrieve its url from Storage and replace it with the url of the loading image in Firestore. The image does show in the chat, however, the loading image is not actually replaced but, instead, it remains in the chat when I want it to be completely replaced, obviously, so that the loading image is no longer there. Here's what I mean, in this image:
As you can see the loading image on top stayed on instead of being replaced by the image underneath it. I think it should be filtered out somehow before I save the new snapshot with the new image url. However, I can not figure out how to do it correctly. I tried to filter it out based on the url of the loading image which is saved locally but since it is saved as a base64 in Storage, it did not work. Neither did using the actual Base64 code as a way to filter it out. So, I need help to solve this issue. The codelab does not really specify this nor is it clear how they do it in their code which is in plain Javascript anyways and I use ReactJS so it may not be 100% suitable.
Here's, I believe, enough code to see what is going on. Let me know if you need more of it.
Here's how I send images to the Chat: (modeled on the Firebase codelab)
sendImageToChat () {
this.state.chatFiles.forEach((file) => {
firebase.firestore().collection('Chats')
.doc(this.state.uid)
.collection('Messages')
.add({
docId: this.state.docId,
imageUrl: loadingLogo,
timestamp: new Date(),
uid: this.state.uid,
name: this.state.displayName,
email: this.state.email
})
.catch((error) => {
this.setState({ writeError: error.message });
})
.then((messageRef) => {
// 2 - Upload the image to Cloud Storage.
const filePath = `users/${this.state.displayName}/${this.state.uid}/${moment().format("MMM Do YY")}/${uuidv4()}/${file.name}`
return firebase.storage().ref(filePath).put(file).then((fileSnapshot) => {
// 3 - Generate a public URL for the file.
return fileSnapshot.ref.getDownloadURL().then((url) => {
// 4 - Update the chat message placeholder with the image's URL.
return messageRef.update({
imageUrl: url,
storageUri: fileSnapshot.metadata.fullPath
});
});
});
}).catch(function(error) {
console.error('There was an error uploading a file to Cloud Storage:', error);
});
})
this.setState({
chatFiles: []
})
document.getElementById('file-1').value = "";
}
Here's how I, then, setState when the loading image is added and then when its url is modified: (Notice how I try to filter out the loadingLogo which is the loading image out of the state but it does not obviously work for the reason explained above).
startChat () {
document.getElementById("myForm").style.display = "block";
const ref = firebase.firestore().collection('Chats').doc(this.state.uid).collection('Messages');
const query = ref.orderBy('timestamp', 'desc').limit(10)
this.unsubFromMessages = query.onSnapshot((snapshot) => {
if (snapshot.empty) {
console.log('No matching documents.');
firebase.firestore().collection('Chats').doc(this.state.uid).
set({
name: this.state.displayName,
uid: this.state.uid,
email: this.state.email
}).then(console.log("info saved"))
.catch((error) => {
console.log("Error saving info to document: ", error);
});
}
snapshot.docChanges().reverse().forEach((change) => {
if (change.type === 'removed') {
console.log(change.doc.data().content)
} else if (change.type === 'added') {
this.setState(state => {
const messages = [...state.messages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
} else if (change.type === 'modified') {
const filteredMessages = this.state.messages.filter(message => message.imageUrl !== loadingLogo)
console.log(filteredMessages)
this.setState(state => {
const messages = [...filteredMessages, {id: change.doc.id, body: change.doc.data()}]
return {
messages
}
})
setTimeout( this.scrollToBottom(), 2000)
}
});
}, (error) => {console.log(error)});
}
This is part of the Chat's JSX:
<div className="chatArea" id='messages'>
{
this.state.messages.map((message, index) => {
return message.body.uid === this.state.uid
?
<div>
{
message.body.imageUrl ?
<img src={message.body.imageUrl} className="message-sent"></img>
:
<p className="message-sent" key={index}>{message.body.content}</p>
}
</div>
:
<p className="message-received" key={index}>{message.body.content}</p>
})
}
<div style={{ float:"left", clear: "both" }}
ref={(el) => { this.myRef = el; }}>
</div>
</div>
I know the issue is not with Firebase but rather with ReactJS. I know I need to remove, filter out, replace or delete that loading image before or after the modified message with the new url is saved to the state. So, please help me figure this out. I am sure many people may encounter this problem.
Thank you!
I figured it out. I might as well delete this question but it may help someone build a chat with ReactJS and Firebase. Anyways, my approach to filter out based on the object property, imageUrl is a viable option. It works! My silly oversight was that I did not add the parent property or object, "body", after the object "message". More specifically, instead of const filteredMessages = this.state.messages.filter(message => message.imageUrl !== loadingLogo), it should be const filteredMessages = this.state.messages.filter(message => message.body.imageUrl !== loadingLogo). You can also try to add an object property that you can use to filter out messages with, for example, allowed: yes or no. If you need more clarification, just ask me, I am glad to help. Happy coding!
I'm creating a test site using Gatsby and Stripe.
At the moment, I have 2 products set up in my Stripe account; I can render these successfully in a Gatsby site, created using the standard starter template.
In my gatsby-config.js file, I have this for the Stripe setup:
resolve: `gatsby-source-stripe`,
options: {
objects: ["Product", "Price"],
secretKey: process.env.STRIPE_SECRET_KEY,
downloadFiles: true,
},
The query and rendering code I'm using is this:
const Skus = () => {
return (
<StaticQuery
query={graphql`
query SkusForProduct {
skus: allStripePrice {
edges {
node {
id
currency
unit_amount
unit_amount_decimal
product {
images
unit_label
description
name
id
}
}
}
}
}
`}
render={({ skus }) => (
<div style={containerStyles}>
{skus.edges.map(({ node: sku }) => (
<SkuCard key={sku.product.id} sku={sku} stripePromise={stripePromise} />
))}
</div>
)}
/>
)
}
I have a separate component (SkuCard), which is used to render the details of each product - the core code looks like this:
const formatPrice = (amount, currency) => {
let price = (amount / 100).toFixed(2)
let numberFormat = new Intl.NumberFormat(["en-US"], {
style: "currency",
currency: currency,
currencyDisplay: "symbol",
})
return numberFormat.format(price)
}
const SkuCard = ({ sku, stripePromise }) => {
const redirectToCheckout = async (event, sku, quantity = 1) => {
event.preventDefault()
const stripe = await stripePromise
const { error } = await stripe.redirectToCheckout({
items: [{ sku, quantity }],
successUrl: `${window.location.origin}/page-2/`,
cancelUrl: `${window.location.origin}/advanced`,
})
if (error) {
console.warn("Error:", error)
}
}
return (
<div style={cardStyles}>
<h4>{sku.product.name}</h4>
<img src={sku.product.images} alt={sku.product.name} />
<p>Price: {formatPrice(sku.unit_amount, sku.currency)}</p>
<p>ID: {sku.product.id}</p>
<button
style={buttonStyles}
onClick={event => redirectToCheckout(event, sku.product.id)}
>
BUY ME
</button>
</div>
)
}
export default SkuCard
My Issue:
Each time I click on the Buy Me button, I'm getting this error in console log:
The steps I've taken:
Confirmed that the ID against the "No such sku" error is indeed one of my test products;
Tried altering the GraphQL query to see if I'm picking up the wrong ID entry - I have tried ones under sku.id and sku.product.id (using the GraphiQL browser), but neither work;
Added a tag to the products displayed to confirm what I believe to be the correct product ID (same as the one shown in the screenshot), can be rendered on screen in the product details - this is displayed without issue;
Scoured the internet to see if anyone else has done similar examples - nothing found;
Used the example code from the main Gatsby site to confirm that I can at least put a single "hard-coded" product through the checkout process - that works. (My chosen method though is to render products dynamically, not as hard-coded items on the page)
Checked the Stackoverflow site: questions have been asked about Stripe & Gatsby, but not found anything yet that is close to this issue.
I'm trying to figure out what is causing this error - can anyone help please?
I have created a simple application using React and Electron that handles few requests, the electron app works fine on dev mode, but during production, there is an issue, all the API calls, written in the code are pointing to file URL: /C:/... instead of proxy mapping to localhost.
Code Snippet is as:
export default class App extends Component {
state = { username: null };
componentDidMount() {
fetch('/api/getUsername')
.then(res => res.json())
.then(user => this.setState({ username: user.username }));
}
render() {
const { username } = this.state;
return (
<div>
<img src={ReactImage} alt="react" style={{ height: '250px' }} />
{username ? <h1>{`Hello there, I'm ${username}`}</h1> : <h1>Loading.. please wait!</h1>}
<Link to="/users">See More users</Link>
</div>
)
}
}
So I have no idea why this is happening, so it would of great help if anyone knows how to resolve it.
Thanks in advance!!
I am trying to load a pdf file into my project, but I am unable to see it. It just keeps showing 'Loading PDF...'
I have added pdfjs web-worker as mentioned in some of their github repo issues, but still no change. I tried building the page by creating a new project suing create-react-app and it seems to be working fine.
import React, { PureComponent } from "react";
import { Document, Page, pdfjs } from "react-pdf/dist/entry.webpack";
import printJS from "print-js";
import requiredFile from "./pdfdemo.pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${
pdfjs.version
}/pdf.worker.js`;
export default class PdfViewer extends PureComponent {
state = {
numPages: null,
pageNumber: 1,
rotate: 0,
scale: 1
};
onDocumentLoadSuccess = ({ numPages }) => {
console.log('this function was triggered')
this.setState({ numPages });
};
render() {
const { pageNumber, numPages, scale, rotate } = this.state;
return (
<React.Fragment>
<div id="ResumeContainer">
<div style={{ width: 600 }}>
<Document
className="PDFDocument"
file={requiredFile}
onLoadError={(error) => {
console.log("Load error", error)
}}
onSourceSuccess={() => {
console.log("Source success")
}}
onSourceError={(error) => {
console.error("Source error", error)
}}
onLoadSuccess={this.onDocumentLoadSuccess}
>
{window === undefined ? <div>nothing here</div> : <Page
pageNumber={pageNumber}
height={600}
className="PDFPage PDFPageOne"
scale={scale}
/>}
</Document>
</div>
</div>
</React.Fragment>
);
}
}
The onSourceSuccess callback seems to be firing on console logging, but none of the other callbacks fire. In the console, I can see an error stating that the window is undefined.
I managed to resolve my issue. The issue seemed to happen due to a variable assignment to the window object at a completely different place in my application. The funny thing is that there wasn't any issue in the application because of that assignment prior to this.
Hope this info. may help someone else.
change node_modules\react-scripts\config\webpack.config.js
add this line from
output: {
++ globalObject: 'this'
}
https://github.com/wojtekmaj/react-pdf/issues/190