[SOLVED] Assigning JSON Request to App Root Data

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!

Try with $setState.

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

Can you share your code?

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

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);
}

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:

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

raise : null

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

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;
      });
    }
  }
);

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

1 Like

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

1 Like