Currently learning svelte and need some assistance - javascript

Currently I am trying to create a hacker news clone (not from the example given on website). Currently I made an api call that returns an array but I can't seem to get rid of the square brackets. For reference my code is below
onMount(() => {
fetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty&limitToFirst=10&orderBy="$key"')
.then((res) => {
return res.text();
})
.then((text) => {
items = text.split(",");
setTimeout(3000);
data = items.filter((val) => {
return val.replace(/[\[\]']+/g, "");
});
});
//console.log(data);
//getData(items).then(console.log);
});
Thanks in advance!

The API provides a JSON object, but you read it as text (res.text()). Replace this with res.json() and the result will automatically be parsed to an array of IDs.
There is no need to manipulate JSON in string form, just parse it/let it be parsed.

Related

javascript: get value inside a nested array

I finally managed to write a raw INSERT-query with sequelize/Apollo/ExpressJS and it returns a json like
{"data":{"createActie":"[[{\"id\":1598}],1]"}}.
I can get to [[{\"id\":1598}],1] by
await this.$apollo
.mutate({
mutation: CREATE_ACTIE_QUERY,
variables: {
// ...
}
})
.then(response => {
console.log(response.data.createActie);
})
but now i want to extract the id and i struggle to say the least (i am not a trained javascript developer, just trying to learn by reading and experimenting)
the solution was adding json.parse...
JSON.parse(response.data.createActie)[0][0].id

How to pass array in the url?

I'd like to filter and want to pass an array to the url.
handleFilter = (search, page = 1) => {
const requestOption = {
method: "GET"
};
fetch("http://127.0.0.1:8000/api/home?search=" + JSON.stringify(search) + "&page=" + page, requestOption)
.then(res => res.json())
.then(data => (
this.setState({
data
})
))
};
Just want to pass the array of data to the api to call the query
I don't know if this will be what exactly you need, but I would...
a.) Join it on a strange character, and pass it as a string.
b.) On the receiving side (client or server), split on that same character.
If you want send it exactly as GET method (not Post), you can form your URL like this:
"http://127.0.0.1:8000/api/home?search[]=value1&search[]=value2&search[]=value3"
That is if you don't want send JSON string.
And what the problem with JSON version or POST method?

Retrieve article object including its image using the Shopify JavaScript Buy SDK custom query

I'm using the shopify-buy SDK to try and fetch the articles off of my Shopify store just using JavaScript on the frontend, following the "Expanding the SDK" directions here: https://shopify.github.io/js-buy-sdk/#expanding-the-sdk.
Using the code below, I am able to retrieve my articles and some of the fields that I need.
// Build a custom query using the unoptimized version of the SDK
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data)
})
However, I really need to pull the featured image for each article as well, and unfortunately, when I add the line article.add('image') in my articlesQuery, the resulting articles data logs null. I tried building a custom productsQuery, and that has a similiar problem - I can retrieve some of the product fields, but when I try add the line product.add('images'), I just get null back from the storefront API.
Does anyone have experience building custom/expanded queries and successfully retrieving images?
Try following:
// Fetch all products in your shop
client.graphQLClient.fetchAll().then((acticles) => {
console.log(acticles);
});
And then check in console what sort of available property names your articles have. If SDK allows you get any image data, there should be for sure anything like imageSrc || imageUrl || img......
Thanks to Rebecca Friedman on the js-buy-sdk repo's github issues section for providing this working solution:
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
article.addField('image', {}, (image) => {
image.add('id')
image.add('originalSrc')
})
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data) // works!
})
Because the image field is its own object, you have to add a callback function to specify the fields you need.

Userless Authentication Foursquare API "Missing access credentials" - 400 error

Bit of a weird one. I'm building a React js app interacting with the Foursquare API, mainly just to learn about React js and APIs.
I'm using Foursquare to get Venue information, that works fine. I also want to use it to get venue photos which is where the fun starts.
The method that processes the original call to venues is as follows. I'm just putting this here for to provide a control as this works fine. It returns the venue information which i process within the app with no problem:
getVenues: (searchTerm) => {
const urlToFetch =
${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602;
return fetch(urlToFetch).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
{
id: item.venue.id,
name: item.venue.name,
// blah
}
));
} else {
return [];
}
})
}
So far, so good, it works fine. However, when I try the same approach accessing the photos endpoint, the method returns a series of objects containing meta which says:
​ code: 400
​​ errorDetail: "Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication for
details."
​​errorType: "invalid_auth"
Suffice to say the information at the link provided doesn't actually give much help :-(
The method I'm using to get the photo information is:
getVenuePhotos: (venueId) => {
const fetchPhotosURL = `${urlPhotos}${venueId}/photos&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
console.log(jsonResponse);
//blah - removed to save space - see method above, it's pretty much the same
})
}
...both are stored in an object in a separate file which the react component imports.
The url vars resolve as follows (asterisks are my addition):
fetchVenuesURL: https://api.foursquare.com/v2/venues/explore?near=london&limit=10&client_id=**** &client_secret=****&v=20180602
fetchPhotosURL: https://api.foursquare.com/v2/venues/4ac518eff964a52064ad20e3/photos&limit=10&client_id=**** &client_secret=****&v=20180602
Does anyone have any idea why this might be happening?
thanks in advance
I think there is a typo in your URL.
Replace
${urlPhotos}${venueId}/photos&limit=10&client...
with
${urlPhotos}${venueId}/photos?limit=10&client...

Array undefined javascript

Hello my problem is that i get undefined , when trying to accsess the array length, but everything works fine when i try to access only the array.
this above do not works ->
console.log(this.ref_number_response[0].info.length);
This works ->
console.log(this.ref_number_response);
and this is the whole
check_ref_number: function () {
this.ref_number_response = [];
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => this.ref_number_response.push({
info: response.data
}));
console.log(this.ref_number_response[0].info.length);
Event.$emit('reference_added', this.ref_number_response);
},
Emit the event after you recieve the data:
check_ref_number: function () {
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => Event.$emit('reference_added',[{info:response.data}]));
}
The problem is that you are getting the data asynchronously, and trying to use the data before it is ready.
You said you are trying to access the the array length, but
this.ref_number_response
is the array, so the only way this console.log(this.ref_number_response[0].info.length); is going to work ( you're trying to get the info property from first element of the array length not the actual array length ) is if info were an array as well. So you'd probably need to do something like:
console.log(this.ref_number_response.length);

Categories

Resources