JSViews - failed to load data after setTimeout - ajax

I referred to the sample code stated in here and I have amended the following code
data = {items: [
{showItem:true, name:"Johnny Depp2"},
{showItem:false, name:"Henry Best"}
]}
to
data = {},
helpers = {
updateItem: function(ev) {
$.observable(this).setProperty("showItem", !this.showItem);
}
};
setTimeout(function () {
data = {items: [
{showItem:true, name:"Johnny Depp2"},
{showItem:false, name:"Henry Best"}
]}
}, 1000);
but I found the initial data could not be loaded, could anyone teach me how to do this? I am simulating the Ajax page load, thanks very much.

Related

How to load AJAX in react

Im trying to get my json result into my react code
The code looks like the following
_getComments() {
const commentList = "AJAX JSON GOES HERE"
return commentList.map((comment) => {
return (
<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id} />);
});
}
How do i fetch AJAX into this?
First, to fetch the data using AJAX, you have a few options:
The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
superagent
reqwest
react-ajax
axios
request
Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:
Fetching initial data (e.g. a list of users).
Fetching data in response to some user interaction (e.g. clicking a
button to add more users).
Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.
Fetching data in response to e.g. an action can be done like this:
var UserGist = React.createClass({
getInitialState: function() {
return {
users: []
};
},
componentWillUnmount: function() {
this.serverRequest && this.serverRequest.abort();
},
fetchNewUser: function () {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
var users = this.state.users
users.push(lastGist.owner.login)
this.setState({ users });
}.bind(this));
},
render: function() {
return (
<div>
{this.state.users.map(user => <div>{user}</div>)}
<button onClick={this.fetchNewUser}>Get new user</button>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Lets say we want to fetch a simple list into our component.
export default MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
lst: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch('url')
.then((res) => {
return res.json();
})
.then((res) => {
this.setState({ lst: res });
});
}
}
We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.
You can use jQuery.get or jQuery.ajax in componentDidMount:
import React from 'react';
export default React.createClass({
...
componentDidMount() {
$.get('your/url/here').done((loadedData) => {
this.setState({data: loadedData});
});
...
}
First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.

Magento 2 checkout shipping rates collection

I'm trying to trigger shipping rates recollection on checkout via 3d party JS code, not Knockout. What's the best way to trigger it?
Now I've replaced template onepage.phtml with custom one and trying this approach, but it doesn't work:
require([
'jquery',
'Magento_Checkout/js/model/quote'
], function($, quote) {
$('#target').on('click', function(e) {
console.log(quote.shippingAddress(quote.shippingAddress()));
});
});
ok, guys. Here is the solution:
require([
'jquery',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-service',
'Magento_Checkout/js/model/shipping-rate-registry',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
], function($, quote, shippingService, rateRegistry, customerAddressProcessor, newAddressProcessor) {
$('#target').on('click', function(e) {
var address = quote.shippingAddress();
// clearing cached rates to retrieve new ones
rateRegistry.set(address.getCacheKey(), null);
var type = quote.shippingAddress().getType();
if (type) {
customerAddressProcessor.getRates(address);
} else {
newAddressProcessor.getRates(address);
}
});
});
i already tried #c0rewell way
Company_Modulename/view/frontend/requirejs-config.js
var config = {
map: {
'*': {
company: 'Company_Modulename/js/myjs'
}
}
};
Company_Modulename/view/frontend/web/js/myjs.js
require([
'jquery',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-service',
'Magento_Checkout/js/model/shipping-rate-registry',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
], function($, quote, shippingService, rateRegistry, customerAddressProcessor, newAddressProcessor) {
$('div[name="shippingAddress.city"] select[name="city2"]').live('change', function(e) {
var address = quote.shippingAddress();
// clearing cached rates to retrieve new ones
rateRegistry.set(address.getCacheKey(), null);
var type = quote.shippingAddress().getType();
if (type) {
customerAddressProcessor.getRates(address);
} else {
newAddressProcessor.getRates(address);
}
});
});
above sciprt successfully force refresh the shipping cost, but the loading takeing forever
error from console
resource-url-manager.js:35 Uncaught TypeError: Cannot read property 'getQuoteId' of undefined
at Object.getUrlForEstimationShippingMethodsByAddressId (resource-url-manager.js:35)
at Object.getRates (customer-address.js:26)
at HTMLSelectElement.<anonymous> (xongkir.js:17)
at HTMLDocument.dispatch (jquery.js:4624)
at HTMLDocument.elemData.handle (jquery.js:4292)
#Ansyori
I have managed to run the estimat-shipping-methods by modifying code like below
require([
'jquery',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-service',
'Magento_Checkout/js/model/shipping-rate-registry',
'Magento_Checkout/js/model/shipping-rate-processor/customer-address',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
], function($, quote, shippingService, rateRegistry,
customerAddressProcessor, newAddressProcessor) {
$('div[name="shippingAddress.city"] select[name="city2"]').live('change', function(e) {
var address = quote.shippingAddress();
// clearing cached rates to retrieve new ones
rateRegistry.set(address.getCacheKey(), null);
var type = quote.shippingAddress().getType();
if (type == 'new-customer-address') {
newAddressProcessor.getRates(address);
}
});
});

Vue.js Retrieving Remote Data for Options in Select2

I'm working on a project that is using Vue.js and Vue Router as the frontend javascript framework that will need to use a select box of users many places throughout the app. I would like to use select2 for the select box. To try to make my code the cleanest I can, I've implemented a custom filter to format the data the way select2 will accept it, and then I've implemented a custom directive similar to the one found on the Vue.js website.
When the app starts up, it queries the api for the list of users and then stores the list for later use. I can then reference the users list throughout the rest of the application and from any route without querying the backend again. I can successfully retrieve the list of users, pass it through the user list filter to format it the way that select2 wants, and then create a select2 with the list of users set as the options.
But this works only if the route that has the select2 is not the first page to load with the app. For example, if I got to the Home page (without any select2 list of users) and then go to the Users page (with a select2), it works great. But if I go directly to the Users page, the select2 will not have any options. I imagine this is because as Vue is loading up, it sends a GET request back to the server for the list of users and before it gets a response back, it will continues with its async execution and creates the select2 without any options, but then once the list of users comes back from the server, Vue doesn't know how to update the select2 with the list of options.
Here is my question: How can I retrieve the options from an AJAX call (which should be made only once for the entire app, no matter how many times a user select box is shown) and then load them into the select2 even if the one goes directly to the page with the select2 on it?
Thank you in advance! If you notice anything else I should be doing, please tell me as I would like this code to use best practices.
Here is what I have so far:
Simplified app.js
var App = Vue.extend({
ready: function() {
this.fetchUsers();
},
data: function() {
return {
globals: {
users: {
data: []
},
}
};
},
methods: {
fetchUsers: function() {
this.$http.get('./api/v1/users/list', function(data, status, response) {
this.globals.users = data;
});
},
}
});
Sample response from API
{
"data": [
{
"id": 1,
"first_name": "John",
"last_name": "Smith",
"active": 1
},
{
"id": 2,
"first_name": "Emily",
"last_name": "Johnson",
"active": 1
}
]
}
User List Filter
Vue.filter('userList', function (users) {
if (users.length == 0) {
return [];
}
var userList = [
{
text : "Active Users",
children : [
// { id : 0, text : "Item One" }, // example
]
},
{
text : "Inactive Users",
children : []
}
];
$.each( users, function( key, user ) {
var option = { id : user.id, text : user.first_name + ' ' + user.last_name };
if (user.active == 1) {
userList[0].children.push(option);
}
else {
userList[1].children.push(option);
}
});
return userList;
});
Custom Select2 Directive (Similar to this)
Vue.directive('select', {
twoWay: true,
bind: function () {
},
update: function (value) {
var optionsData
// retrive the value of the options attribute
var optionsExpression = this.el.getAttribute('options')
if (optionsExpression) {
// if the value is present, evaluate the dynamic data
// using vm.$eval here so that it supports filters too
optionsData = this.vm.$eval(optionsExpression)
}
var self = this
var select2 = $(this.el)
.select2({
data: optionsData
})
.on('change', function () {
// sync the data to the vm on change.
// `self` is the directive instance
// `this` points to the <select> element
self.set(select2.val());
console.log('emitting "select2-change"');
self.vm.$emit('select2-change');
})
// sync vm data change to select2
$(this.el).val(value).trigger('change')
},
unbind: function () {
// don't forget to teardown listeners and stuff.
$(this.el).off().select2('destroy')
}
})
Sample Implementation of Select2 From Template
<select
multiple="multiple"
style="width: 100%"
v-select="criteria.user_ids"
options="globals.users.data | userList"
>
</select>
I may have found something that works alright, although I'm not sure it's the best way to go about it. Here is my updated code:
Implementation of Select2 From Template
<select
multiple="multiple"
style="width: 100%"
v-select="criteria.reporting_type_ids"
options="globals.types.data | typeList 'reporttoauthorities'"
class="select2-users"
>
</select>
Excerpt from app.js
fetchUsers: function() {
this.$http.get('./api/v1/users/list', function(data, status, response) {
this.globals.users = data;
this.$nextTick(function () {
var optionsData = this.$eval('globals.users.data | userList');
console.log('optionsData', optionsData);
$('.select2-users').select2({
data: optionsData
});
});
});
},
This way works for me, but it still kinda feels hackish. If anybody has any other advice on how to do this, I would greatly appreciate it!
Thanks but I'm working on company legacy project, due to low version of select2, I encountered this issue. And I am not sure about the v-select syntax is from vue standard or not(maybe from the vue-select libaray?). So here's my implementation based on yours. Using input tag instead of select tag, and v-model for v-select. It works like a charm, thanks again #bakerstreetsystems
<input type="text"
multiple="multiple"
style="width: 300px"
v-model="supplier_id"
options="suppliers"
id="select2-suppliers"
>
</input>
<script>
$('#app').ready(function() {
var app = new Vue({
el: "#app",
data: {
supplier_id: '<%= #supplier_id %>', // We are using server rendering(ruby on rails)
suppliers: [],
},
ready: function() {
this.fetchSuppliers();
},
methods: {
fetchSuppliers: function() {
var self = this;
$.ajax({
url: '/admin_sales/suppliers',
method: 'GET',
success: function(res) {
self.suppliers = res.data;
self.$nextTick(function () {
var optionsData = self.suppliers;
$('#select2-suppliers').select2({
placeholder: "Select a supplier",
allowClear: true,
data: optionsData,
});
});
}
});
},
},
});
})
</script>

How to refresh content when using CrossroadJS and HasherJS with KnockoutJS

I was following Lazy Blogger for getting started with routing in knockoutJS using crossroads and hasher and it worked correctly.
Now I needed to refresh the content using ajax for Home and Settings page every time they are clicked. So I googled but could not find some useful resources. Only these two links
Stack Overflow Here I could not understand where to place the ignoreState property and tried these. But could not make it work.
define(["jquery", "knockout", "crossroads", "hasher"], function ($, ko, crossroads, hasher) {
return new Router({
routes:
[
{ url: '', params: { page: 'product' } },
{ url: 'log', params: { page: 'log' } }
]
});
function Router(config) {
var currentRoute = this.currentRoute = ko.observable({});
ko.utils.arrayForEach(config.routes, function (route) {
crossroads.addRoute(route.url, function (requestParams) {
currentRoute(ko.utils.extend(requestParams, route.params));
});
});
activateCrossroads();
}
function activateCrossroads() {
function parseHash(newHash, oldHash) {
//crossroads.ignoreState = true; First try
crossroads.parse(newHash);
}
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
$('a').on('click', function (e) {
crossroads.ignoreState = true; //Second try
});
}
});
Crossroads Official Page Here too I could not find where this property need to be set.
If you know then please point me to some url where I can get more details about this.

How to reduce data table load time?

I am working with data table plugin. Initially what I tried is to update the data table plugin from a flat text file. The text file would look like below.
{
"data":[
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
},
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
}
]
}
I have a HTML file inside this I am writing JavaScript like below.
$(document).ready(function() {
var table=$('#app-table').DataTable( {
"bProcessing": true,
"bPaginate":true,
"bServerSide": false,
"sAjaxSource": "./data/arrays.txt",
"deferRender": true,
"columns": [
{ "data": "reference" },
{ "data": "application" },
{ "data": "applicationType" },
],
"order": [[ 3, "desc" ]],
"ordering": true,
"bFilter": true
} );
The data table is rendering fine until am not having more than 20,000 rows in the table. As the number of rows will increase in the table then data table took more time to load.
What I notices by going through with several site is that we can reduce the load time by using server side processing and for that I need to go with a server which is not possible in my case because I am rendering data from a flat text file. Then I thought to look for static data storage.
So coming to the problem is using indexedDB can we resolve the performance issue and if answer is yes than can anyone let me know how?
I am able to work with indexedDB but unable to integrate with jQuery data table. I mean what I need to make change in the JavaScript. If we can make server side processing with indexedDB then what will be the script?
first read your local file in the following manner:
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
Then, use JQuery to parse "allText" into JSON.
Refer this link for parsing into JSON.
Now, create database using "indexedDB API" as mentioned below:
var request = indexedDB.open("<mention_your_db_name_here");
request.onupgradeneeded = function() {
// The database did not previously exist, so create object stores and indexes.
var db = request.result;
var store = db.createObjectStore("books", {keyPath: "reference"});
var titleIndex = store.createIndex("by_reference", "reference", {unique: true});
// Populate with initial data.
store.put({reference: "#VIP-123", application: "Development Aspects", applicationType: "Current Application"});
};
request.onsuccess = function() {
db = request.result;
};
for more details on "indexedDB API", please refer this link

Resources