Store returned array as a const - javascript

How do I set my returned data from a JSON file to a const so I can use it in other functions. I'm able to console.log but how do I proceed? The end goal is to be able to use data.purchase_orders and loop through the data (ie - price_list)
data.json
{
"purchase_order": [
{
"id": "1",
"external_number": "1000",
"status": "Created",
"price_list": [
{
"id": "msrp",
"name": "retail price",
"currency": "USD"
}
],
"shipments": [
{
"id": "1",
"external_number": "10000",
"status": "Created",
"tracking_number": "Z1F2"
},
{
"id": "2",
"external_number": "9000",
"status": "In Transit",
"tracking_number": "PL21F"
}
]
}
]
}
index.html
<div id="shipments"></div>
<script>
const data_file = 'data.json';
async function fetchPO(){
const reponse = await fetch(data_file);
const data = await response.json();
const PO = data.purchase_orders.forEach((PODetails) => {
console.log(PODetails);
//^this displays key and value of my JSON data_file
})
displayShipments(PO);
}
fetchPO();
function displayShipments(shipmentsList){
document.getElementById("shipments").innerHTML = `
${Object.keys(shipmentsList).map(function (shipments)
return `${shipments.id}
<p>${shipments.tracking_number}</p>`
)}
}
`
}
</script>

One approach is to return the data from the async fetccPO() and store the promise in a variable.
A promise can be used as many times as you want.
Simplified example:
async function fetchUsers() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
return response.json();
}
// makes request and stores promise in variable
const usersPromise = fetchUsers();
async function logAddress() {
// promise can be used many times
const users = await usersPromise;
console.clear()
console.log(users[0].address);
}
async function logUserName() {
const users = await usersPromise;
console.clear()
console.log(users[0].name);
}
<button onclick="logAddress()">Log first user address</button>
<button onclick="logUserName()">Log first user name</button>

Related

How to get the lastest product from API

I have a component to render only the latest product gets from API:
const about = ({products}) => {
const data = products.attributes
console.log(data)
return (
<div>
<h1>{data.Name}</h1>
<p>{data.Description}</p>
<p>{Number(data.Price).toLocaleString('it-IT', {style : 'currency', currency : 'VND'})}</p>
<p>{data.Release}</p>
<p>{data.Expire}</p>
<p>{data.Close ? "Close" : "Open"}</p>
</div>
);
}
export async function getStaticProps() {
const data = await fetch(myAPI)
const res = await data.json()
const products = res.data[0]
return {
props: {products}
}
}
export default about;
The JSON from API looks like this:
{
"data": [
{
"id": 1,
"attributes": {
"Name": "Vĩ Hoạ",
"Description": "Vĩ Hoạ",
"Price": "30000",
"Release": "2022-05-04",
"Expire": "2022-05-26",
"Close": false,
"createdAt": "2022-05-09T22:28:09.622Z",
"updatedAt": "2022-05-10T05:50:38.430Z",
"publishedAt": "2022-05-10T05:50:12.353Z"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 1
}
}
}
The highest id from JSON is the latest product, I haven't figured out how to resolve this JSON for getting the latest product.const products = res.data[x] is used to get the specific product based on x, like an index. This is my temporary solution but not flexible to get the latest one!
The best solution is descending data by createdAt when getting data from the API. Otherwise, you can use this method.
const about = ({products}) => {
const data = products.attributes
console.log(data)
return (
<div>
<h1>{data.Name}</h1>
<p>{data.Description}</p>
<p>{Number(data.Price).toLocaleString('it-IT', {style : 'currency', currency : 'VND'})}</p>
<p>{data.Release}</p>
<p>{data.Expire}</p>
<p>{data.Close ? "Close" : "Open"}</p>
</div>
);
}
export async function getStaticProps() {
const data = await fetch(myAPI)
const res = await data.json()
const products = res.data.sort((a, b) => b.id - a.id)[0]
return {
props: {products}
}
}
export default about;

Dialogflow fulfillment not responding to keywords

I am trying to make sense of how the fulfillment works, and I cannot get the responses from the if statements to work. Whenever I write the keyword, the default response I get is Not available.
The webhook for the intent is enabled, the entity is 'hooked' in the intent as well.
What am I missing here?
const functions = require('firebase-functions');
const { dialogflow } = require('actions-on-google');
const app = dialogflow();
const WELCOME_INTENT = 'Default Welcome Intent';
const USER_MESSAGE_ENTITY = 'UserMessage';
app.intent(WELCOME_INTENT, (conv) => {
const userMessage = conv.parameters(USER_MESSAGE_ENTITY).toLowerCase();
if (userMessage == 'hey') {
conv.ask('Hey there');
} else if (userMessage == 'greetings') {
conv.ask('Greetings, how are you');
} else if (userMessage == 'evening') {
conv.ask('Good evening');
}
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app);
{
"responseId": "8499a8f2-b570-4fb2-9f3c-262bd03db01e-c4f60134",
"queryResult": {
"queryText": "hey",
"action": "input.welcome",
"parameters": {
"UserMessage": "hey"
},
"allRequiredParamsPresent": true,
"intent": {
"name": "projects/wandlee-zad-rekrutacyjne--euol/agent/intents/d76ffc6c-c724-4fa4-8c9b-7178a2d7f9b7",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 76
},
"languageCode": "pl",
"sentimentAnalysisResult": {
"queryTextSentiment": {
"score": 0.2,
"magnitude": 0.2
}
}
},
"webhookStatus": {
"code": 14,
"message": "Webhook call failed. Error: UNAVAILABLE."
}
}
I don't know where you got conv.parameters(USER_MESSAGE_ENTITY).
The parameters of the intent are accessible as a second function argument. It is going to be a map:
app.intent(WELCOME_INTENT, (conv, params) => {
const userMessage = params[USER_MESSAGE_ENTITY].toLowerCase();
// ...
})
``

How to Change json with Javascript

https://github.com/smelukov/loftschool-example
i am creating my project in this envorement .
I created friends.json file in the root folder .
friends.json
{
"name": "Иван",
"lastName": "Петров",
"value": "5.24"
},
{
"name": "Иван",
"lastName": "Петров",
"value": "6.00"
},
{
"name": "Иван",
"lastName": "Петров",
"value": "4.54"
}
]
index.hbs
<div id="prev-results"></div>
<button id="loadButton">Load Results</button>
index.js
const loadButton = document.querySelector("#loadButton");
const result = document.querySelector('#prev-results');
loadButton.addEventListener('click', () => {
fetch('friends.json')
.then(response => {
if (response.status >= 400){
return Promise.reject();
}
return response.json();
})
.then(friends => {
result.innerHTML = '';
for (let friend of friends) {
const friendNode = createFriendNode(friend);
result.appendChild(friendNode);
}
})
.catch(() => console.error('Что-то пошло не так'));
});
function createFriendNode(friend) {
const div = document.createElement('div');
div.classList.add('friend');
div.textContent = `${friend.name} ${friend.lastName}`;
const result = document.createElement("a");
result.textContent = `${friend.value}`;
result.classList.add("result");
const label = document.createElement("a");
label.classList.add("result-label")
label.textContent = "mL/min/1.73m²";
div.appendChild(result);
div.appendChild(label);
return div;
}
Now i can get objects from friends.json and add them to the DOM , but how do i change friends.json with javascript ?
The client can't write back to the static file it's being served. This would be the use case for a database. For a JSON-like document object store that can be manipulated, you can use something like MongoDB.

asyncData with apollo query returns an object but not an array

I am using apollo to get my data in a Nuxt.js project, using asyncData
import homeQuery from '~/apollo/queries/home'
export default {
async asyncData({app}) {
const homeresult = await app.apolloProvider.defaultClient.query({
query: homeQuery
})
return { home: homeresult.data.home }
},
data () {
return {
home: {}
}
}
this works fine when the result of the query is an object, for example the above is:
{
"data": {
"home": {
title": "Home"
}
}
}
However, if the query result is an array:
{
"data": {
"home": [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
}
}
nothing gets returned. (I also tested data () { return { home: [] } } )
Do I have to treat arrays differently, and how should I correctly write the asyncData?
I have absolutely no idea what changed... but when I tried again that code, I had no more problems with arrays as results.

how to get data inside json object inside object?

i try to get some track_list data inside object JSON using Musixmatch API
here is my code
"body": {
"track_list": [
{
"track": {
"track_id": 194169151,
"track_name": "Blinding Lights",
"track_name_translation_list": [],
"track_rating": 100,
"commontrack_id": 104185748,
"instrumental": 0,
"explicit": 0,
"has_lyrics": 1,
"has_subtitles": 1,
"has_richsync": 1,
"num_favourite": 3237,
"album_id": 37216011,
"album_name": "After Hours",
"artist_id": 13937035,
"artist_name": "The Weeknd",
"track_share_url": "https://www.musixmatch.com/lyrics/The-Weeknd-3/Blinding-Lights?utm_source=application&utm_campaign=api&utm_medium=rickyreza%3A1409619798940",
"track_edit_url": "https://www.musixmatch.com/lyrics/The-Weeknd-3/Blinding-Lights/edit?utm_source=application&utm_campaign=api&utm_medium=rickyreza%3A1409619798940",
"restricted": 0,
"updated_time": "2020-04-10T08:31:57Z",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_id": 7,
"music_genre_parent_id": 34,
"music_genre_name": "Electronic",
"music_genre_name_extended": "Electronic",
"music_genre_vanity": "Electronic"
}
}
]
}
}
},
i just want to check if i can geat the data inside a track by doing lyric.album_name. and tried to get the album and i got this kind of things album_name as undefined. here is my main.js
main.js
function main() {
// initialize the data
const baseUrl = "https://api.musixmatch.com/ws/1.1";
const apiKey = "78fa4727ab9c4495d4fc07dae75f775b";
const chartTrack = "chart.tracks.get?chart_name=top&page=1&page_size=5&country=jp&f_has_lyrics=1"
const getLirik = () => {
fetch(`${baseUrl}/${chartTrack}&apikey=${apiKey}`)
.then(response => {
return response.json();
})
.then(responseJson => {
// console.log(responseJson);
// trackList.track_list = responseJson.message.body.track_list
console.log(responseJson.message.body.track_list.track);
// console.log(responseJson.message.body.track_list.track.album_name);
renderAllData(responseJson.message.body.track_list);
})
.catch(error => {
console.log(error);
})
}
/*
for making a new html DOM
*/
const renderAllData = (lyrics) => {
const lirikElement = document.querySelector("#popularLyrics");
lirikElement.innerHTML = "";
lyrics.forEach(lyric => {
lirikElement.innerHTML += `
<div>${lyric.album_name}</div>
`
})
}
getLirik();
}
export default main;
How do i can get all thos track_name and stuff inside track?
You forgot the property .track in your lyrics object. Try this
...
<div>${lyric.track.album_name}</div>
i checked the api call https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=jp&f_has_lyrics=1&apikey=78fa4727ab9c4495d4fc07dae75f775b the tracklist returns an Array of objects, where each object has only one key track
something like this track_list = [{track:{}},{track:{}}]
use ${lyric.track.album_name} it should work
you forgot one property, but you can do less nesting using destructuring in the function, this is a litle modification of your code:
const renderAllData = (trackList) => {
const lirikElement = document.querySelector("#popularLyrics");
lirikElement.innerHTML = "";
trackList.forEach(({ track }) => {
lirikElement.innerHTML += `
<div>${track.album_name}</div>
`;
});
};
renderAllData(data.body.track_list);

Categories