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
Related
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.
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.
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.
Lets presume I am sending a POST request to /api/products. My body is like below
{
"products":[
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
},
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
}
]
}
In my route I am trying to convert the above products to a JSON Object;
Below is my server code
const { products } = req.body;
console.log(JSON.parse(products));
but this gives me the error "message": "Something went wrong Unexpected token o in JSON at position 1"
How can i achieve this??
Cheers
Screenshots added
Tried below as well. But no luck
Nothing works.
const products = req.body;
console.dir(typeof products); // 'object'
console.dir(products); // { products: '[object Object]' }
const { products } = req.body;
console.dir(typeof products); // 'string'
console.dir(products); // '[object Object]'
postman developer console is as below. Doesnt seem to be an issue
{
"products":[
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
},
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
}
]
}
It's not a JSON object, JSON objects are surrounded by curly braces.
if you return
{"products": [ { "id":"5f5065e44a12bd00232bcc6g", "status":"true" }, { "id":"5f5065e44a12bd00232bcc6g", "status":"true" } ]}
then it will be worked.
The best thing to do would be to fix what you're sending to /api/products by putting {} around it, like this:
{
"products":[
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
},
{
"id":"5f5065e44a12bd00232bcc6g",
"status":"true"
}
]
}
Now it's valid JSON, and you can convert it via JSON.parse:
const obj = JSON.parse(req.body);
console.log(obj);
const { products } = obj;
or just
const { products } = JSON.parse(req.body);
Notice I'm using the entire body there. That will give you an object with a property (products) with the array of products. Alternatively, instead of parsing it manually, you could use middleware that would parse it automatically so that req.body is the parsed result, in which case it's just:
console.log(req.body);
const { products } = req.body;
If for some reason you can't send correct JSON, but it will always be in the form you've shown, you could add the {} afterward like this:
const obj = JSON.parse("{" + req.body + "}");
console.log(obj);
const { products } = obj;
or just
const { products } = JSON.parse("{" + req.body + "}");
but I strongly recommend not doing that, not least because you can't use middleware and sending malformed data around tends not to be ideal. Instead, send valid JSON in the first place.
Look at the content of your variable products, and your debugger.
In this line you're using an object destructuring assignment but the right hand side isn't an object, it's a string:
const { products } = req.body;
Try this instead:
const { products } = JSON.parse(req.body);
EDIT you appear to be using Express middleware or similar. There's a good chance that your object has already been converted from JSON so you just need your original line and not the JSON.parse line.
const { products } = req.body;
console.dir(products);
Figured it out.
Thanks to #T.j and #Alnitak was able to get this sorted. Used
let obj = req.body;
But i had an issue with my validator.
body('products')
.trim()
.not()
.isEmpty()
.withMessage('Custom product must have a main product'),
In the above code using .trim() converted the products into a string and once I removed the trim() it works perectly. Thanks all for the thoughts
Try with JSON.stringify()
Otherwise, maybe you were declaring an object (const { products }), try without the {}
I have created an axios request to my api for two routes. Using the response data I sort posts into the correct columns inside an array. This all works as it should but then when I come to assigning the value of this array to an array inside data() i get the following error;
TypeError: Cannot set property 'boardPosts' of null
at eval (SummaryBoard.vue?2681:90)
at wrap (spread.js?0df6:25)
So I figured maybe something was wrong with the array I was trying to assign. So I tried to assign boardPosts a simple string value and I still get the same error. Why can I not set the value of boardPosts inside my axios response?
my code;
import axios from 'axios';
export default {
name: 'SummaryBoard',
data() {
return {
boardPosts: '',
}
},
created() {
this.getBoardData();
},
methods:
getBoardData() {
function getBoardColumns() {
return axios.get('http://localhost:5000/api/summary-board/columns');
}
function getBoardPosts() {
return axios.get('http://localhost:5000/api/summary-board/posts');
}
axios.all([getBoardColumns(), getBoardPosts()])
.then(axios.spread(function(columnData, postData) {
let posts = postData.data;
// add posts array to each object
let columns = columnData.data.map(obj => ({...obj, posts: []}));
posts.forEach((post) => {
// If column index matches post column index value
if(columns[post.column_index]){
columns[post.column_index].posts.push(post);
}
});
console.log(columns);
this.boardPosts = 'hello';
}))
.catch(error => console.log(error));
}
}
}
That's because you're using not using an arrow function in axios.spread(...). This means that you do not preserve the lexical this from the VueJS component, as function() {...} will create a new scope for itself. If you change it to use arrow function, then the this in the callback will refer to your VueJS component instance:
axios.all([getBoardColumns(), getBoardPosts()])
.then(axios.spread((columnData, postData) => {
// Rest of the logic here
}))
.catch(error => console.log(error));