Currently, I'm implementing cloudinary in a react app using cloudinary-react.
For this project, I was given this code which I've added to my API helper file. However, I am getting errors when I try to use it:
export const resolveSimpleCloudinaryUrl = id => {
return cloudinary.Cloudinary.new({
use_root_path: true,
private_cdn: true,
cloud_name: 'mycloudname',
secure: true,
}).url(id);
};
The first error states:
'cloudinary' is not defined
For the cloudinary error, I created a variable using the cloudinary base URL:
export const resolveSimpleCloudinaryUrl = id => {
let cloudinary = `https://res.cloudinary.com/`;
//remaining code...
This removes the first error, but now I get a new error:
Unhandled Rejection (TypeError): Cannot read property 'new' of undefined
What is the proper way to implement this? I haven't been able to figure this out yet. I haven't found anything in the documentation specific to what I've been given. Thank you in advance
Related
I'm creating a booking reference for the user to download after successfully making a booking. It looks like this in the browser:
However, after using html2canvas to get a screenshot of the component in React, I get this:
I suspect the issue has to do with the fact that the static map's use is protected by an API key, causing issues to render the image in an external view.
This is the callback that fires on hitting the share button, which for now just downloads the png (which is then converted to pdf using jsPDF):
const share = () => {
const input = document.getElementById("trip-summary");
if (input === null) return;
html2canvas(input!).then((canvas) => {
var image = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
const pdf = new jsPDF();
// #ts-ignore
pdf.addImage(image, "PNG", 0, 0);
pdf.save("download.pdf");
});
};
It looks like an external source of content. You should set the allowTaint option to true.
html2canvas(input, { allowTaint: true }).then(...);
Just wanted to add to the answer above.
It achieves exactly what I want, but you just need to set useCORS to true in the options as well
html2canvas(input!, { allowTaint: true, useCORS: true }).then(...)
, otherwise you'll get
Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
In my project I'm using React-Dropzone-Component (https://github.com/felixrieseberg/React-Dropzone-Component) based on Dropzone.js.
I'm using this component because I'm developing a SharePoint webpart and there is already an example based on this solution on Microsoft PnP GitHub repository.
Anyway, the upload is working fine, but sometimes, mainly when I keep a web page opened for a couple of minutes doing nothing, I receive an error trying to upload new files. I retry an upload and it fails returning Server responded with (0) code error. I also see on Google Chrome console an ERR_CONNECTION_RESET error. If I try to upload 5 files in second instance, I get error on first 2-3 and then the remaining files works fine. Weird.
I've already investigated my network, but there are no failures. I've also tried with 3 different networks and I've received the same error.
I've also updated the component with the latest Dropzone.js (5.7.2).
This is my code:
let componentConfig = {
iconFiletypes: this.props.fileTypes.split(','),
showFiletypeIcon: true,
postUrl: _context.pageContext.web.absoluteUrl,
autoProcessQueue: true
};
var djsConfig = {
headers: {
"X-RequestDigest": digest1
},
addRemoveLinks:false
};
let myDropzone;
let eventHandlers = {
// This one receives the dropzone object as the first parameter
// and can be used to additional work with the dropzone.js
// object
init: function(dz){
myDropzone=dz;
},
sending: async function (file, xhr) {
var fileName = file.name;
fileName = fileName.replace(/[&\/\\#,+()$~%='":*?<>{}]/g, "");
if (file.size <= 10485760) {
// small upload
await web.getFolderByServerRelativeUrl("/test/"+_listName).files.add(fileName, file, true).then(_ => console.log("Ok!"));
} else {
// large upload
await web.getFolderByServerRelativeUrl("/test/"+_listName).files.addChunked(fileName, file, data => {}, true).then(_ => console.log("Ok!"));
}
},
error:function(file,error,xhr){
file.status = myDropzone.ADDED;
myDropzone.removeFile(file);
myDropzone.enqueueFile(file);
}
};
<DropzoneComponent eventHandlers={eventHandlers} djsConfig={djsConfig} config={componentConfig}>
<div className="dz-message icon ion-upload">Drop files here to upload</div>
</DropzoneComponent>
If I can't prevent this ERR_CONNECTION_RESET error, I would like to set up an automatic retry for these files. The code I've posted above is not working fine or it returns "Uncaught Error: This file can't be queued because it has already been processed or was rejected.".
Is there a solution or a good way to set up a retry?
I have an application generated using JHipster 6.x with React JS as UI. In many screens I am fetching data using redux methods like
Method:
export const getStudentsByCriteria: ICrudSearchAction<IStudent> = (query, page, size, sort) => ({
type: ACTION_TYPES.SEARCH_STUDENTS,
payload: axios.get<IStudent>(`${apiUrl}?${query}${sort ? `&page=${page}&size=${size}&sort=${sort}` : ''}`)
});
Call:
(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "firstName,asc") as IPayload<IStudent>).payload.then((response) => { ... }
It's been working quite fine but all of sudden I started getting error: TS2339: Property 'then' does not exist on type 'IPayload | ((dispatch: any) => IPayload)'.
Property 'then' does not exist on type 'IPayload'
Simply calling .then gives compile error in MS Code but works locally without any issue however won't allow to build war because of compile errors
(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "firstName,asc").then((response) => { ... }
This should return IPayload and IPayload.payload.then ... must work. It's been working, it's pretty strange that it stopped working all of a sudden.
I got it working by converting returned object to Promise as given in below code:
(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "rollNo,firstName") as unknown as Promise<IStudent[]>).then((response) => {
this.setState({
sectionStudents: (response as any).value.data
});
});
Had to use ... as unknown as Promise. VS Code shows response type as IStudent[] but it gives error on runtime when I try to call map function. (map is not supported for IStudent[]). Since response type at compile is IStudent[], it doesn't have value property and gives error, therefore it had to be converted to 'any' to get value.data. Debugging the code unraveled this.
Why this code stopped returning IPayload is still a mystery for me.
I want to upload an image to Azure Blob Storage using React.
I've tried a lot of examples and none of them work.
The one that seemed the best was this one but still didn't manage to get it working on React.
What I'm trying right now is to use the createContainerIfNotExists method just to test and the error is Cannot read property createBlobServiceWithSas of undefined
My code is the following:
import AzureStorage from 'azure-storage';
const account = {
name: 'x',
sas: 'x',
};
const blobUri = `https://${account.name}.blob.core.windows.net`;
const blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, account.sas);
export const createContainer = () => {
blobService.createContainerIfNotExists('test', (error, container) => {
if (error) {
// Handle create container error
} else {
console.log(container.name);
}
});
};
export default createContainer;
According to my research, because you develop A React application, we can not use the createBlockBlobFromBrowserFile method. We just can use the method in the browser. For more details, please refer to the document.
According to the situation, I suggest you use the other method(such as uploadStreamToBlockBlob) to upload image with V10 sdk. For more details, please refer to https://learn.microsoft.com/en-us/javascript/api/#azure/storage-blob/?view=azure-node-latest
I am fairly new to React, and have not done any extensive web development in years, so am struggling with a (probably) basic web issue:
I am implementing a Stripe based payment flow in a React web app (written in Typescript), and have hit a roadblock on step 2 (adding a redirect to checkout client-side).
The quickstart guide instructs me to insert the following script tag on my website, which I have done through inserting the tag inside the <head> tag:
Checkout relies on Stripe.js. To get started, include the following
script tag on your website—it should always be loaded directly from
https://js.stripe.com:
<script src="https://js.stripe.com/v3/"></script>
The next step is where I am having a problem (using the ESNext syntax since this is in a Typescript project):
Next, create an instance of the Stripe object by providing your publishable API key as the first parameter:
const stripe = Stripe('pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu');
I would like to access Stripe through a service worker, rather than a component directly. However, trying to initialise the stripe instance is not working. I have tried:
importing the Stripe module in various ways, which hasn't worked
adding a dependency on #types/stripe, which seems to prevent the compiler complaining
Currently, my StripeService.ts file has the following code:
const stripe = Stripe("SOME_KEY");
export const redirectToCheckout = (sessionId: string) => {
return stripe.redirectToCheckout(
{
sessionId: sessionId,
});
};
Localhost instance is giving this error:
/src/services/stripe/StripeService.ts
Line 12: 'Stripe' is not defined no-undef
Any suggestions on how I can resolve this issue? I have looked into the react-stripe-elements wrapper, but that is geared towards providing UI components, whereas I only want the Stripe checkout API call behaviour.
Bare Minimum
Minimum implementation is to declare Stripe using any:
declare class Stripe {
constructor(...args: any[]);
redirectToCheckout(...args: any[]): any;
}
const stripe = new Stripe("pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu");
stripe.redirectToCheckout({
sessionId: sessionId
})
Stronger Typings
You can of course expand this by more explicitly typing the parts that you need:
declare class Stripe {
constructor(publicKey: string);
redirectToCheckout({
sessionId
}: {
sessionId: string;
}): Promise<{ error: Error }>;
}
const stripe = new Stripe("pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu");
stripe.redirectToCheckout({
sessionId
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
Try using the windows object instead:
var stripe = window.Stripe("pk_test_h4naRpZD1t2edp2HQKG2NrZi00rzz5TQJk");
For a service file, you would just add stripe to package.json, then in the file would do:
import Stripe from "stripe";
const stripe = Stripe("SOME_KEY");
export const redirectToCheckout = (sessionId: string) => {
return stripe.redirectToCheckout(
{
sessionId: sessionId,
});
};
You would use the public key in the client side, and the secret key in the server side. You should keep stripe object (Stripe('pk_test_sdjxyNjHWmRefdkUNYuS53MA00Ot1f9HOu')) in your state somehow to be able to retrieve it later.
An example call could be like this:
client side
const {paymentMethod, error} = await this.state.stripe.createPaymentMethod('card', cardElement, {
billing_details: {
name: 'Jenny Rosen',
},
});
StripeService.makePayment(paymentMethod);
server side
import Stripe as "stripe";
const stripe = Stripe("SOME_KEY");
export const makePayment = (paymentMethod: object) => {
...
};