Reputation: 331
I am trying to download an image from AWS, display it in my React component, and then on a button click, load a new image. The problem I am facing is that every time I go to load a new image, the page loads image after image, and won't stop rerendering with new images.
Here is my code for the landing page:
import React from 'react';
import Background from './Media/marmaduke2.jpg';
import Comic from'./Comic.js';
import { useState, useEffect } from 'react';
export default function RandomarmLanding() {
const [score, setScore] = useState(0)
const [isReal, setIsReal] = useState(false)
const [caption, setCaption] = useState('')
async function getComics() {
const response = await fetch('http://127.0.0.1:5000/comics')
const data = await response.json()
setCaption(data['caption'])
setIsReal(data['is_real'])
}
function GuessYes() {
if (isReal == true) {
setScore(score + 1)
}
}
function GuessNo() {
if (isReal == false) {
setScore(score + 1)
}
}
useEffect(() => {
getComics()
},[])
return(
<div style={{backgroundImage: `url(${Background})`}}>
<Comic caption={caption}/>
<button onClick={GuessYes}>Yes</button>
<button onClick={GuessNo}>No</button>
<button onClick={getComics}>get comics</button>
<h2>{score}</h2>
</div>
)
}
Here is my code for the Comic component:
import React from 'react';
import comic from './Media/comic.png';
export default function Comic (props) {
return(
<div>
<img src={comic}/>
<h1>{props.caption}</h1>
</div>
)
}
Here is the code that is actually downloading the image:
import boto3
def download_comic(num):
s3 = boto3.resource('s3')
s3_client = boto3.client('s3')
bucket = s3.Bucket('bucket_name')
s3_client.download_file('bucket_name',f'{num}.png', '/path/my-app/src/components/Randomarm/Media/comic.png')
Any thoughts on what might remedy this? Thanks for the help!
Instead of downloading the image to display it, I am just showing the image from my s3 bucket, using <img src=bucketimage.gif'/>
. This way I avoid the constant rerendering all together.
Upvotes: 0
Views: 553
Reputation: 331
I solved it. Instead of downloading the image, I am just displaying the image from my s3 bucket. That way I avoid downloading the image all together.
Upvotes: 1
Reputation: 936
I believe it's because of the state being changed in useEffect
inside the method getComics
where you are setting the caption.
Upvotes: 2