Reputation: 187
I´m new to REST API and on the current project where I can create gallery categories and images inside the gallery I bumped into a problem. I have multiple objects within the parent array as seen below. Some of them containing image.
[]
0:
0: {path: "test", name: "test"}
1: {path: "puli", image: {…}, name: "puli"}
2: {path: "animalsg", name: "animalsg"}
3: {path: "animals", image: {…}, name: "animals"}
4: {path: "Animals", image: {…}, name: "Animals"}
5: {path: "sdfsf", name: "sdfsf"}
6: {path: "viki", name: "viki"}
7: {path: "pul", image: {…}, name: "pul"}
8: {path: "testik", name: "testik"}
__proto__: Object
length: 1
__proto__: Array(0)
Is there a way to fetch all the name values from each object and also assign it an id?
Can you please help me modify this useEffect
for this purpose?
useEffect(() => {
const tempAlbum = [];
fetch('http://someapi.xy/gallery')
.then(response => response.json())
.then(data => tempAlbum.push('???'));
}, [])
Upvotes: 0
Views: 66
Reputation: 197
If I understood right, you would want to do something like this
useEffect(() => {
const tempAlbum = [];
fetch('http://someapi.xy/gallery')
.then(response => response.json())
.then(data => { data[0].forEach(
(item,i) => {
tempAlbum.push({name: item.name, id: i})
})
});
}, [])
About the id, this approach is using the same array index as id, that could work for you unless you need this id to render this array on your React application, in which case using the index is not recommended, so you could use a library like uuid to generate an id on the fly, it's very simple to use and does not require configuration.
Upvotes: 1
Reputation: 371
If what you are trying to do is simply get an tempAlbum to have an array of like [{ name: 'rockers', id: '1234'}, ...] then you can do:
data.flat().forEach((x, idx) => tempAlbum.push({ name: x.name, id: idx }));
That should work for you.
Upvotes: 0