I try to get images from Instagram and build a gallery on my site.
myCode:
function Instagram() {
const instagramData = async () => {
const url = `https:/site.com/...`;
const data = await fetch(url);
const feed = await data.json();
console.log(feed);
};
instagramData();
return (
<>
{feed.map((feed) => { //it's not feed :(
return (
<div key={feed.id}>
<img src={feed.media_url} alt="" />
</div>
);
})}
</>
);
}
export default Instagram;
my Array from console:
{data: Array(25), paging: {…}}
data: Array(25)
0: {id: '123', media_url: 'https://stuff.com/1', permalink: 'https://www.instagram.com/p/1/'}
1: {id: '456', media_url: 'https://stuff.com/2', permalink: 'https://www.instagram.com/p/2/'}
....
length: 25
[[Prototype]]:Array(0)
paging
:
{cursors: {…}, next: 'https://website/abcd'}
[[Prototype]]: Object
'feed' is not the right var to use. But somehow i must extract the array from the function and store it like a normal obj. But how?
What magical code I need to do the .map ?
CodePudding user response:
Please implement useState
hook to store feeds, and make your API call inside useEffect
hook.
import { useState } from "react";
function Instagram() {
const [feeds, setFeeds] = useState([]);
useEffect(() => {
const instagramData = async () => {
const url = `https:/site.com/...`;
const data = await fetch(url);
const feeds = await data.json();
setFeeds(feeds);
};
instagramData()
}, []);
return (
<>
{feeds.map((feed) => {
return (
<div key={feed.id}>
<img src={feed.media_url} alt="" />
</div>
);
})}
</>
);
}
export default Instagram;
CodePudding user response:
Call the function instagramData()
inside useEffect
hook
import {useEffect} from 'react';
useEffect(() =>
instagramData();
},[])