Coding data Into a dataset and then displaying it in a table

Hello,

I have been trying to retrieve data from an api (which I have done successfully), and then performing calculations with the data. I created a table and linked it to a dataset. I am hoping someone can explain how I would take my calculated value and through javscript, insert it to the dataset, so that it can then display in my table. I have been using setFieldValue, which has been working perfectly, however I am having trouble setting the field value for different rows. I can only seem to set the field value for the first row, and then not any other rows in the dataset

You should get into details as this question is too general.

To be more specific, I am creating a table and would like to add the %change for each stock ticker to the table and dataset. I’m


attaching my code below

Can you copy&paste the code?

import {getStockInfo} from ‘backend/serviceModule’ ;

var airlines = [ “AAL” , “UAL” , “DAL” ];

$w.onReady( function () {
//TODO: write your page related code here…

});

export function button1_click_1(event, $w) {
getStockInfo(airlines[ 0 ])
.then(currencyInfo => {

    $w( "#dynamicDataset" ).setFieldValue( "todays_change" , (parseInt(currencyInfo[ "Time Series (Daily)" ][ "2020-07-24" ][ "4. close" ],  10 )).toFixed( 2 )); 
}) 

getStockInfo(airlines[ 1 ])
.then(currencyInfo => {

    $w( "#dynamicDataset" ).setFieldValue( "todays_change" , (parseInt(currencyInfo[ "Time Series (Daily)" ][ "2020-07-24" ][ "4. close" ],  10 )).toFixed( 2 )); 
}) 

getStockInfo(airlines[ 2 ])
.then(currencyInfo => {

    $w( "#dynamicDataset" ).setFieldValue( "todays_change" , (parseInt(currencyInfo[ "Time Series (Daily)" ][ "2020-07-24" ][ "4. close" ],  10 )).toFixed( 2 )); 
})

//BACKEND

import {fetch} from ‘wix-fetch’ ;

export function getStockInfo(currency) {
const url = 'https://www.alphavantage. co/query?function=TIME_SERIES_DAILY&symbol=’ + currency + ‘&apikey=DJ5GPL5CAQI0Q652’ ;
console.log( "Url: " + url);

return fetch(url, {method: ‘get’ })
.then(response => response.json());

}

If it’s your real api key you should change it.

As for your question, I don’t see where you save it.

This isn’t my final api, I will be using. Just a free one I’m experimenting with. it would not allow me to post a link here so I had to add a space in the api link when sharing it here. That could be the issue

as for saving it, would that solve my problem. The first problem I am trying to address is putting AAL % change in row 1 column 2,
UAL % change in row 2 column 2,
and DAL % change in row 3 column 2. I don’t believe I have written or am aware of code that allows me to input the data into the different rows. thanks for all your help

From someone from outside it’s hard to understand the question.
Please try to simplify it.
What do you currently have? What are you trying to do?
Do you have the calculated data and you just don’t know how to bind it to the table? Or what?

Sorry for the confusion. I have created the table which I have linked to my dataset. In my dataset I have already include three stock tickers in one column, and want to add their corresponding % changes in the other column. This should be displayed to my chart. Currently with the code I sent you, the % change data for AAL is being displayed. However, the % change data for UAL and DAL (the second and third row) is not being displayed. I am trying to have the AAL data in row 1, UAL data in row 2, and DAL data in row 3. So I do have thw data I need, but The problem is for UAL and DAL I don’t believe the data is being assigned to the correct cell in the dataset.

To clarify, I am adding the current output. The issue is that when I run my program, the UAL and DAL % change is blank (Im trying to fill the value in the cell, as I did with AAL)

The informations from https://www.wix.com/corvid/forum/community-discussion/setting-custom-table-values could help you.

I adapt it to your question and also make the code better.

To only update current view it could/should be something like(untested):

import {getStockInfo} from 'backend/serviceModule';

//TODO: dynamicaly update this value(on page load)
var dateToRead = "2020-07-24";

function getValueFromResponse(currencyInfo){
    return parseInt(currencyInfo["Time Series (Daily)"][dateToRead]["4. close"], 10).toFixed(2);
}

$w.onReady(function () {
    $w("#dynamicDataset").onReady(()=>{
	$w("#table1").rows.forEach((row, index) => {
            //TODO: change row["ticker"] to real fieldname on table
	    getStockInfo(row["ticker"]).then(currencyInfo => {
                row["todays_change"] = getValueFromResponse(currencyInfo);
            });
	});
    });
});

Or if you want to update the database (saved values also) by button click, something like (again untested):

import {getStockInfo} from 'backend/serviceModule';

$w.onReady(function () {
    //make sure button is only pressed if dataset is ready
    $w("#button1").disable();
    $w("#dynamicDataset").onReady(()=>{
        $w("#button1").enable();
    });
});

//TODO: dynamicaly update this value(on page load), or get/set it from a input field inside of button1_click_1
var dateToRead = "2020-07-24";

function getValueFromResponse(currencyInfo){
    return parseInt(currencyInfo["Time Series (Daily)"][dateToRead]["4. close"], 10).toFixed(2);
}

//TODO: change all occurense of "ticker" with reald DB fieldname (if it's not "ticker")

//async recoursive recursivefunction
function updateEntry(tickerToUpdate){
    getStockInfo(tickerToUpdate).then(currencyInfo => {
        //verify same item is still active (otherwise value is saved incorrect)
        var activeTicker = $w("#dynamicDataset").getCurrentItem()["ticker"];
        if (activeTicker == tickerToUpdate){
            //update value
            $w("#dynamicDataset").setFieldValue("todays_change", getValueFromResponse(currencyInfo));
            if ($w("#dynamicDataset").hasNext()){
                //next call save internal
                $w("#dynamicDataset").next()
                    .then(() => {
                        //call function for next entry (recoursion)
                        updateEntry($w("#dynamicDataset").getCurrentItem()["ticker"]);
                    })
                    .catch(() => {
                        console.log("Error on update to next entry, abort update.");
                        //reactivate button
                        $w("#button1").enable();
                    });
            } else {
                //save current/last item and reactivate button
                $w("#dynamicDataset").save()
                    .then(() => {$w("#button1").enable();})
                    .catch(() => {
                        console.log("Error saving change on last entry");
                        $w("#button1").enable();
                    });
            }
        } else {
            //some other logic changed active item while wait on response from getStockInfo...
            console.log("Error: active entry changed by other logic, was:" + ticker + " is now: " + activeTicker + ", try to update this one");
            updateEntry(activeTicker);
        }
}

export function button1_click_1(event, $w) {
    //make sure button is not pressed again while update still active
    $w("#button1").disable();
    //TODO: if you wan update db on page load, the following lines could be moved to inside $w("#dynamicDataset").onReady(... above
    //make sure first item is active, so all entries are updated
    $w("#dynamicDataset").setCurrentItemIndex(0)
        .then(() => {
            //call function for first entry, this recursively call for other entries
            updateEntry($w("#dynamicDataset").getCurrentItem()["ticker"]);
        })
        .catch(() => {
            console.log("Change to first item failed, abort update");
            //reactivate button
            $w("#button1").enable();
        });
}

was fun writing this (initially search for help for my own problem…)