I am currently facing a rather strange issue and was wondering if anyone would know the solution. I am making an api call to my Django backend to get details on profiles
export const ProfilesPage = () => {
const classes = useStyles()
useEffect(() => {
getProfiles()
})
const [profiles, setProfiles] = useState([])
let imgLink = ''
let getProfiles = async () => {
let response = await fetch('http://127.0.0.1:8000/api/profiles', {
method: "GET"
})
let data = await response.json()
// console.log(data[0].profile_image)
imgLink = 'http://127.0.0.1:8000' data[0].profile_image
console.log(imgLink)
}
return (
<div className={classes.root}>
ProfilesPage
<img alt='profile' src={imgLink} />
</div>
)
}
the last line of my getProfiles function I am console.loging the image link. The link is appearing on my console and when i click on it, the correct image is being opened in my browser. I am unsure why react is not displaying the image when the link is clearly working. Thank you,
CodePudding user response:
Try using state instead of let img = ''
Example:
const [img, setImg] = useState([]);
useEffect(() => {
const getProfiles = async () => {
let response = await fetch('http://127.0.0.1:8000/api/profiles', {
method: "GET"
})
let data = await response.json()
// console.log(data[0].profile_image)
imgLink = 'http://127.0.0.1:8000' data[0].profile_image
setImg(imgLink)
}
getProfiles();
}, [profiles])
Then use the state in your return:
return (
<div className={classes.root}>
ProfilesPage
<img alt='profile' src={img} />
</div>
)
CodePudding user response:
Because you are trying to store the image URL in imgLink
it's being reset to empty string each time the component is re-rendered.
What you can try is storing the image URL in a state which will persist between each render.