[SOLVED] Assigning JSON Request to App Root Data


#1

Hello,

New programmer here so bear with me :slight_smile:

I am requesting JSON data and can display it in the console no problem.
app.request.json(‘http://localhost:3000/allevents’, function (mydata) {
app.data.raise = mydata;
console.log(mydata);
});

I then want to use it under the name ‘raise’ throughout my app and have assigned it to app.data.raise.
However when I print app.data to the console I can see ‘raise’ but when I print app.data.raise to the console I get undefined.

console.log(app.data);
console.log(app.data.raise);

image

I have tried app.data.raise[0] and app.data.raise[0].name etc.

I can use $root.products.x no problem but $root.raise.x is not working. I am using the tabbed views template.

Many thanks in advance!


#2

Try with $setState.

https://framework7.io/docs/router-component.html#component-context

Can you share your code?


#3

Hi pvtallulah,

Thanks for replying. I will look into $setState.

Here is a link to my code for app.js https://codeshare.io/5Q0BkW

Cheers


#4

app.request.json is async function, when you calling console.log(app.data.raise) on end script request has not yet completed and the data has not been received. It is necessary to call functions after the completion of the request

app.request.json('http://localhost:3000/allevents', function (mydata) {
  app.data.raise = mydata;
  console.log(mydata);
  jsonParse(mydata);
});

function jsonParse(data){
	console.log(app.data.raise);
}

or

app.request.json('http://localhost:3000/allevents', jsonParse);

function jsonParse(data){
	app.data.raise = data
	console.log(app.data.raise);
}

#5

Hi Overman,

Thanks for the reply.

I see what you are saying. Do you know how I can place my request.json within the Framework7 app main instance and assign it to raise so I can then use $root.raise on a template with handles for {{city}}, {{venue}} etc.

Something like this but currently I receive cannot set property ‘raise’ of undefined:


#6

Во-первых в app нужно дописать в return {

raise : null

Во-вторых ваш подход может не работать, т.к. запрос пройти позже, чем открытие компонента и данные не обновятся. Нужно использовать $setState.


#7

There is no sense to do request inside of data method. Just do it right after app init:

var app = new Framework7(
  ...
  on: {
    init: function (f7) {
      f7.request('...', (mydata) => {
        f7.data.raise = mydata;
      });
    }
  }
);

#8

Кто будет так делать, не забывайте, что так нельзя делать при версии < 3.6.6 и Cordova.


#9

Thank you very much everyone! Now it is working :grin: