So Im trying to get insta posts by url
This is my code:
const data = get('${url}'})
console.log(data)
Data that i get in console (post with only 1 picture):
[
{
media: "example.com"
}
]
const items = data.media
so the issue is right here:
const Post_MP4 = items.map((item, index) => {
if(item && item.includes(".mp4"))
return ({name: 'video${index}.mp4', attachment: item})
else if(item && item.includes(".jpg"))
return ({name: 'image${index}.jpg', attachment: item})
}).filter(item => item)
When the insta post has only 1 picture i get an error(items.map is not a function) but when the post has more than 1 picture I dont get any error.
Data when the post has more than 1 picture:
{
media: ["example", "example2"]
}
What can I do to not get any error by using this code. Thank you.
The map method is to be used on an array. When there's only one picture, you return a string, which do not have the array method. But when there's more than one, you return an array which indeed has the map method.
As mentioned in the comments, check if media is an array with the isArray method.
The "TypeError: map is not a function" occurs when we call the map() method on an object that is not an array. To solve the error, console.log the value you're calling the map() method on and make sure to only call the map method on valid arrays.
Related
I am fetching my data from external API as usual and this is the typical way I do it:
Fetch API:
const [tshirts, setTshirts] = useState([]);
const fetchData = () => {
fetch('apiEndpoint')
.then((response) => response.json())
.then((data) => {
setTshirts(data[0].clothes.regular.top); // path to my array
})
.catch((error) => {
console.log(error);
});
};
React.useEffect(() => {
fetchData();
}, []);
Map through an array:
const tshirtArray = tshirts.tShirt; // specifying the path
const listItems = tshirtArray.map((item) => <li>{item}</li>);
<ul>{listItems}</ul>
Example of data structure:
[
{
id: 1,
clothes: {
regular: {
top: {
sleeveless: [],
tShirt: [
"image-path-here"
],
.....
.....
.....
When I first time execute the code it works, but after some time or after refreshing the page I get an error of TypeError: Cannot read properties of undefined (reading 'map')
Why is that undefined? The path is correct and fetching the array should be as well. Can not find the reason of it not working.
I don't have reputation to comment, so let me try to clarify it for you through an answer. As #sojin mentioned, you cannot use tshirts.Tshirt since your state is of array type and arrays can't be used like objects, meaning that if there was an object of lets say exampleObject = { type: "shirt", color: "white } you could call it with exampleObject.type. Since you have an array of objects in your state (top that you are saving to state is still object which contains tShirt array), you first have to use index (to tell which object you want to use from the state array) and then you can use it like you wanted. For example, in your example there are 1 objects in state array. Array indexes start at 0. So you could do tshirts[0].tShirt to get the tShirt array from that object.
However, I would edit your code a bit. Instead of using tshirtArray constant, just do listItems from your state:
const listItems = tshirts.map((item) => {item.tShirt[0]});
Note: I've just used index 0 here to demonstrate the finding of the first item in tShirt array. If you want to see all tShirt image paths, then you may need to do nested mapping or other similar solutions.
learning React but I'm trying to map an array of objects in a dropdown box.
I'm getting a "Uncaught TypeError: ids.map is not a function".
Why am I getting this error when I have set the loadedIds I get from the GET request into useState's setIds?
https://jsfiddle.net/4jh9c6dv/53/
Thank you for helping a beginner :')
function Dropdown ()
{
const [ids, setIds] = React.useState([]);
React.useEffect(() => {
request.get(endpointIds).then((response) => {
setIds(response.data);
const loadedIds = [];
for (const id in response)
{
loadedIds.push({
id: ids,
});
}
setIds(loadedIds);
});
}, []);
const idsList = ids.map((id) =>
(
<option>id</option>
));
You do not need to use setIds(response.data);. Remove that.
response.data is not an array, response.data.ids is. That is why you get the error.
EDIT : Use for of instead of for in.
for of is used to iterate over items of an array/iterable object.
for in is used to iterate over index.
response.data should be response.data.id
you also forgot curly braces {id}
I am working with React.js and YouTube API. I get a collection of objects from the API but I want to add a 'check' field to every object. I used the below code -
await axios.get('https://youtube.googleapis.com/youtube/v3/search', {
params: {
part: 'snippet',
q: sTerm,
type: 'video',
key: KEY
},
})
.then(response => {
let i=0;
response.data.items.forEach(item=>{
response.data.items[i]['check']=true
i++;
})
console.log(response.data.items) //gives correct output with check field
console.log(response.data.items[0].check) //gives undefined instead of true
console.log(response.data.items[0]['check']) //gives undefined instead of true
})
What should I do to access the 'check' field value?
Update: This is my response
Finally what worked for me is creating a new array as suggested by a now deleted answer.
.then((response) => {
myItems=response.data.items.map(
item => ({...item, check: true})
);
console.log(myItems);
You can use javascripts Array.prototype.map instead of forEach to transform every value in your items array:
.then(response =>
response.data.items.map(
item => ({...item, check: true})
)
)
This should return on the top line where you are awaiting the axios call the array of items where each item.check equals true.
I am returning an array from an async call in my action which then gets passed down to the reducer and finally back into the React. However, whenever I try to access the elements inside I get an error. My first guess was maybe my async call is wrong so I console.log everywhere. But everything seems fine except when I try to map over the array.
Here is the sequence of steps:
Dispatch Action:
.then(feeds => {
console.log('Sending data to dispatch');
console.log(`Testing this function -> ${JSON.stringify(feeds)}`);
dispatch({
type: 'RETRIEVE_FEEDS',
payload: feeds,
});
Initially feeds is an empty array in my reducer which then gets populated with this array.
Reducer:
case 'RETRIEVE_FEEDS': {
return { ...state, feeds: action.payload };
}
Now in my mapStateToProps I receive the initial empty array and then the populated array from dispatch.
const mapStateToProps = ({ feedState }) => {
const { feeds } = feedState;
console.log(`FeedState -> ${JSON.stringify(feedState.feeds)}`);
console.log(`Is Array -> ${Array.isArray(feedState.feeds)}`);
console.log(`Going to map through the array`);
feedState.feeds.map(feed =>{
console.log(`Feed -> ${JSON.stringify(feed)}`)
console.log(`Feed ID -> ${feed.feedID}`)
});
return { feeds };
};
My only issue is that whenever I try to get something from the array it gets undefined.
These are my logs:
FeedState -> []
Is Array -> true
Going to map through the array
Sending data to dispatch
Testing this function -> [[{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}],[{"feedID":"reYEcurssCV32WyQgOYp","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:46:13.655Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]]
FeedState -> [[{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}],[{"feedID":"reYEcurssCV32WyQgOYp","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:46:13.655Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]]
Is Array -> true
Going to map through the array
Feed -> [{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]
Feed ID -> undefined
It looks like, from your logs, that each item in feedState.feeds is an array. So feed.feedID won't work. feed[0].feedID would work.
Also your .map function should return something and you should do something with your mapped array. i.e. result of feeds.map
I'm receiving data with axios like this:
getData() {
Axios.get(
'/vue/get-data/',
{
params: {
categories: this.category,
activeFilters: this.activeFilters,
}
}
).then((response) => {
this.banners = response.data;
this.setBanner();
})
},
Then I get this:
When I try console.log(response.data.length) I get undefined. What could
be going on here very weird!
When I look in my vue-devtools banners has 2 objects:
So how can response.data.length be undefined?
You are getting object not array that why .length is not working, and you are getting as undefined
this.banners = response.data[0];// for first
Or loop over this, to get each object's data
for(var i in response.data){
console.log(response.data[i]);
}
If to get each value is not your purpose , and you want to just size check this answer