This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I have been staring at this assignment for an hour and a half and I know what I want to do next but not sure how to.
function getPhotoFromId(photoId) {
return `https://picsum.photos/id/${photoId}/200/200`;
}
const PHOTO_LIST_URL = "https://picsum.photos/list";
function Photos(props) {
const [photos, setPhotos] = React.useState([]);
React.useEffect(() => {
const photosFetch = fetch(PHOTO_LIST_URL)
const json = photosFetch.json();
setPhotos(json)
}, []);
}
I have to make a photowall using the URL. Now, what I'm planning to do is to map out the contents of the URL and then use a spread operator to concat it to a new array (since I can't push it directly due to immutability) but I am not sure if I'm on the right steps and what I should do next.
The lifecycle should be called after the initial render which is why I left a blank array at the end of useEffect and the array of photos is being fetched. I mainly need help with setting the array of photos to the state once it has been fetched.
Edit. I got the array to show up in my console log with this
React.useEffect(() => {
fetch(PHOTO_LIST_URL)
.then((response) => response.json())
.then((photoArray) => {
console.log(photoArray);
})
}, [PHOTO_LIST_URL]);
Edit 2: Used better naming
Edit 3: Trying out this block of code.
const [photos, setPhotos] = React.useState([]);
React.useEffect(() => {
const newPhotos = {
}
fetch(PHOTO_LIST_URL)
.then((response) => response.json())
.then((photoArray) => {
setPhotos(photoArray);
})
.then(setPhotos((state) =>state.concat(newPhotos)))
}, [PHOTO_LIST_URL]);
Edit: Solved
const [photos, setPhotos] = useState([]);
useEffect(() => {
fetch(PHOTO_LIST_URL)
.then((response) => response.json())
.then((photoArray) => {
setPhotos(photoArray);
});
}, []);
Subreddit
Post Details
- Posted
- 3 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...