How to append fetched image URL to img src - javascript

I am trying to append the fetched url from a minted NFT jsons metadata to a <img src so that the picture can then be seen inside the dapp. I have fetched the tokenId from the receipt and then used the tokenId with the ipfs link to grab the metadata and then return the image URL which all works fine I have just hidden some code with the personal information.
.then(async(receipt) => {
console.log(receipt);
setMinted(true)
const tokenIds = {ipfslink}.json
const tokenMetadataResponse = await fetch(`/config/json/${tokenIds}.json`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const tokenMetadata = await tokenMetadataResponse.json();
const image = tokenMetadata.image;
console.log(image)
const nftHolder = document.getElementById("nft_template").content.cloneNode(true)
nftHolder.querySelector("img").src = image.toString();
nftHolder.querySelector("img").alt = tokenMetadata.description
document.getElementById("nfts").append(nftHolder)
When I console.log the link I get the correct Image Url but when I try to append I get this error enter image description here (I can not embed yet my apologies) All help appreciated thank you.
Here is where the img element lies, I have a video that plays upon the receipt of the transaction that indicates a successful mint for the animation that I intend to play with the image.
So when the receipt occurs it turns the minted state to true which you can see in the above code
{minted ? <s.Screen id="nft">
<MintingVideo src="/config/mint.mp4" autoPlay={true} ></MintingVideo>
<template id="nft_template">
<section>
<h1></h1>
<a href="" target="_blank">
<img src={null} alt=""></img>
</a>
</section>
</template>
</s.Screen>
: null}

I have solved this I believe by giving the image a placeholder source that is just a white background.
<s.Screen> //Screen holding all components displayed whether minted is true or not
{minted ? <s.Screen id="nft">
<MintingVideo src="/config/mint.mp4" autoPlay={true} ></MintingVideo>
<NftBox id="nftBox"src="/config/images/plah.png"></NftBox>
</s.Screen>
: null}
And then here is where I target the element and change the source to the one provided
const tokenMetadataResponse = await fetch(`/config/json/${tokenIds}.json`, {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const tokenMetadata = await tokenMetadataResponse.json();
let image = tokenMetadata.image
if(image.startsWith("ipfs://")) {
image = `https://ipfs.io/ipfs/${tokenMetadata.image.split("ipfs://")[1]} `
};
console.log(image)
const nftHolder = document.getElementById("nft").content
const dNftBox = document.getElementById("nftBox");
dNftBox.src = image;

Related

Stripe Payment element show saved card

I am using laravel with stripe payment element. I am trying to show the saved cards for the customers that we already have. I have followed the stripe docs and found how I can show it on checkout. But the problem is that I am not getting the saved cards for the customer. And instead I am facing an error on my console as:
When authenticating with an ephemeral key, you must set the Stripe-Version header to an explicit API version, such as 2020-08-27
I have checked and changed lot of versions from here:
$ephemeralKey = \Stripe\EphemeralKey::create(
['customer' => "$user->stripe_customer_id"],
['stripe_version' => '2019-11-05']
);
I changed the version to different version that I can see on my stripe dashboard:
This is my Js Initialize function:
// Fetches a payment intent and captures the client secret
async function initialize() {
// Customize the appearance of Elements using the Appearance API.
const appearance = { /* ... */ };
// Enable the skeleton loader UI for the optimal loading experience.
const loader = 'auto';
const { clientSecret, customerOptions } = await fetch("{{ route("user-create-stripe-element-payment") }}", {
method: "POST",
headers: {
"Content-Type" : "application/json",
"accept" : "application/json",
'X-CSRF-TOKEN': "{{ csrf_token() }}",
'stripe_version':"2019-11-05"
},
body: JSON.stringify({ totalCharge:total }),
}).then((r) => r.json());
elements = stripe.elements({
clientSecret,
appearance,
loader,
customerOptions
});
const paymentElement = elements.create("payment");
paymentElement.mount("#payment-element");
}
And I am also using the betas which is given in the documentation:
const stripe = Stripe("{{env('STRIPE_KEY')}}", {
betas: ['elements_customers_beta_1'],
});
But this error is not going away. And its not even populating the Payment element.
Please help me debug this or if someone has any suggestion to check what is going on here.
Thanks in advance.
You are not providing an API version in your JS here
const stripe = Stripe("{{env('STRIPE_KEY')}}", {
betas: ['elements_customers_beta_1'],
});
change the above code to
const stripe = Stripe("{{env('STRIPE_KEY')}}", {
betas: ['elements_customers_beta_1'],
apiVersion: 'Your Version Here'
});
In your case, it should be something like this
const stripe = Stripe("{{env('STRIPE_KEY')}}", {
betas: ['elements_customers_beta_1'],
apiVersion: '2019-11-05'
});
You can read more here. https://stripe.com/docs/api/versioning?lang=node
It is for nodejs but the API version override will work in the same way.

SPA Routing Vanilla JavaScript

I'm doing a SPA project using Vanilla JS. It is a kind of notice board platform where there are categories. Each category will have a list of posts that users have uploaded.
This is the URL format for each category: base_URL/{category}/{pageNum}.
This is the URL format for each post: base_URL/board/${board_id}.
I have to extract the board_id some how upon the user clicking it and use it in the URL (ex: http://example.com/board/31890adfa).
From searching I found out I'll be using the history API.
Then I'll extract the board_id from the URL and send a request to view that post:
const fetchBoardDetails = async (board_id) => {
await fetch(`http://${base_URL}/board/${board_id}`, {
method: "GET",
headers: { "Content-Type": "application/json" },
}).then(async (res) => {
const data = await res.json();
root.innerHTML = `
<h1>${data.title}</h1>
<ul>
<li>${data.category}</li>
<li>${data.date}</li>
<li>${data.place}</li>
<li>${data.fee}</li>
</ul>
`
}
My problem is, how do I get the board_id in step 1 to use in step 2? I think it has to do with URL routing and I've tried to figure it out but can't wrap my head around it.

React component renders before I can set src of image

I have this application that flashes a series of cards. Some have questions with text. No problem there obviously. But the image source is being retrieved from firebase. On each render I check if it has a question with text, or with an image and if it has an image I query the database for the downloadURL and insert that as the source. If I insert it hard coded it works fine, if I console log the response it's accurate. My problem is I believe that the component renders before I can insert the source dynamically. Code is below. And yes, I know with that many conditionals it looks like a christmas tree and is probably really bad practice.
To save some reading I'll splice it where I make the request here...
useEffect(() => {
if ("imageHolder" in active) {
const asyncFunc = async () => {
setLoading(true);
setImage(true);
await storageRef
.child(active.imageHolder)
.getDownloadURL()
.then(function (url) {
imageSrc = url;
console.log("url returns ", url);
})
.catch(function (error) {
console.log(error);
});
};
asyncFunc();
setLoading(false);
}
}, [active, getQuestions, correctAnswer]);
And where I insert it here
) : image ? (
loading ? (
<h1>Loading</h1>
) : (
<img alt="" src={imageSrc} className="d-inline-block align-top" />
)
) : (
<h3>{active.question}</h3>
)}
</div>
<div className="answerGrid">
{loading ? (
Thanks for any advice at all. And stay healthy!
It might be helpful to see the rest of the code, but given the provided snippets, I'm assuming the problem is with how the imageSrc variable is getting set.
Have you tried managing the imageSrc as state? E.g.
const [imageSrc, setImageSrc] = useState('')
// then use setImageSrc after getting the url
await storageRef
.child(active.imageHolder)
.getDownloadURL()
.then(function (url) {
setImageSrc(url)
console.log("url returns ", url);
})
I think simple decision to this will be adding a logical "or" operator in src
like this
<img alt="" src={imageSrc || ''} className="d-inline-block align-top" />

React get and show attached files in Rails

seems a simple problem but, i don't know why this is causing a little stress, anyway.
here is situation:
after get the attachments on the Post.show in rails
async getAttachments() {
// this.setState({showProgress: true})
let auth_token = window.localStorage.getItem("auth_token");
let post_id = this.props.match.params.id;
fetch(`/posts/${post_id}/attachments`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
}
})
.then(response => response.json())
.then(json => {
this.setState({
attachments: json.attachments,
image: json.attachments.image,
thumb: json.attachments.image.thumb,
url: json.attachments.thumb.url
});
})
.catch(error => {
console.error(error);
});
}
i decide to render it as usual
with {this.state.attachments}
but did not rendered.
so i tried to map and then i tried
var attachments = this.state.attachments.map(a => {
return (
<div key={a.id}>
<img source={a.thumb} />
<img source={a.url}>{a.url}</img>
</div>
);
});
the thing is ever rails carrierwave attachment/files. create a object inside the array and many people still have doubt how to grab and render these files.
The HTML image tag uses an attribute named src, not source. That's your problem.
Aside: Consider this snippet of your code:
this.setState({
attachments: json.attachments, // OK, keep
image: json.attachments.image, // bad path into the object
thumb: json.attachments.image.thumb, // bad path into the object
url: json.attachments.thumb.url // bad path into the object
});
The three lines starting with image, thumb, and attachment should be deleted.
The result of using the code without deleting those lines will be that your state looks like:
{
attachments: <an array of attachments>, // correct, wanted, should keep
image: undefined,
thumb: undefined,
url: undefined
}
This is because json.attachments is an array so it does not have any data at the paths you are calling. By "path into the object" I merely mean a sequence of keys to call in sequence of dot notation.

React pdf onclick download

I have a problem with react. I have a program that embeds a pdf and a download button. I want to download the pdf upon clicking the button.
Instead, my program redirects me to another page where you download the pdf, meaning it exists in the app but I just want to stay in the same app and download the pdf in my app.
Are there any plugins that I can use to do this?
Please find below my code:
<div>
<object data={this.props.file} type='application/pdf'>
<embed src={this.props.file} type='application/pdf' />
</object>
{
this.props.author ==='bot' ?
<a href={this.props.file} download={this.props.file}>
<input alt='download' type={'image'} src={download} />
</a>
:
''
}
</div>
You can handle this with basic HTML. you do not need any plugins. I prefer using reactstrap instead of bootstrap.
import { Row, Col } from "reactstrap";
<Row>
{/* off set will middle the col */}
<Col md={{ size: 8, offset: 2 }}>
<div >
<a
//this will save the file as "your_cv.pdf"
download="your_cv.pdf"
//put the path of your pdf file
href="/static/resume.pdf"
//reactstrap classes. add green button
className="btn btn-success"
>
Download
</a>
</div>
<iframe
style={{ width: "100%", height: "800px" }}
src="/static/resume.pdf"
>
{" "}
</iframe>
</Col>
</Row>
You can download the pdf file as a blob and temporarily create a link to download that blob as a file. You can do something like:
fetch(this.props.file, {
method: 'GET',
headers: {...headers},
})
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'YOUR_PDF_NAME.pdf');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
});
Not sure how your pdf hosting server is configured, you can set the headers of request accordingly.
Try the following method using fetch call and save the file using FileReader object
fetch(this.props.file, {
method: "GET",
headers: {
Accept: "application/pdf",
"Content-Type": "application/pdf",
},
}).then(response => response.blob())
.then(response => {
var blob=response
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
window.open(base64data);
}
})
.catch(error => {
console.error(error);
});

Categories

Resources