i have some actions in reflux actions, this is my actions
var BeritaActions = Reflux.createActions({
'getListBerita': {
children: [
'actions', 'completed', 'failed'
]
},
'getBerita': {
children: [
'actions', 'completed', 'failed'
]
},
});
BeritaActions.getListBerita.listen(function(param)
{
return BeritaUtil.listBerita(param)
.on('error', this.failed)
.end(this.completed);
});
BeritaActions.getBerita.listenAndPromise(function(id)
{
return BeritaUtil.read(id)
.on('error', this.failed)
.end(this.completed);
});
this is my store, and listen to actions
Reflux.createStore({
onprogress: false,
type: null,
init()
{
this.listenTo(BeritaAct.getListBerita.completed, this.getInitData);
this.listenTo(BeritaAct.getListBerita.failed, this.getInitErrorData);
},
setType(type)
{
return this.type = type;
},
getCurrentData()
{
return _data;
},
getInitData(field)
{
console.log(field)
let data = JSON.parse(field.text);
if(data.meta.code == 200)
{
if(typeof _data[this.type] == 'undefined')//first open
{
//console.log('first')
_data[this.type] = data.data;
}else//on load more = merging data
{
//console.log(_data[this.type])
_data[this.type] = update(_data[this.type], {$merge: data.data});
}
this.trigger(_data);
}else
{
Toas.error({title:data.meta.message, content:''});
}
},...
so i execute actions in my components
React.createClass({
getInitialState()
{
if(Progress.isAjax())
{
Progress.onProgress(true);
BeritaStore.setType('list');
BeritaAct.getListBerita({});
}else
{
//not ajax
}
return {
showloader: {display: 'none'},
shownext: {display: 'block'}
};
},..
store can listen actions so well and can return on my react component. but when i check network inspect, i got the action request many time, i don't know what happening ?
ok guys i solved that problem, let going to getInitData function
getInitData(bind, field)
{
console.log(field)
}
i add parameter on getInitData function, so after i console.log() second paramater, i get the data
Related
I have a React context I am testing that runs a single function to check for an application update. The checkForUpdate function looks like this:
async function checkForUpdate() {
if (isPlatform('capacitor')) {
const maintanenceURL =
'https://example.com/maintenance.json';
const updateURL =
'https://example.com/update.json';
try {
const maintanenceFetch: AxiosResponse<MaintanenceDataInterface> =
await axios.get(maintanenceURL);
console.log('maintain', maintanenceFetch);
if (maintanenceFetch.data.enabled) {
setUpdateMessage(maintanenceFetch.data.msg);
return;
}
const updateFetch: AxiosResponse<UpdateDataInterface> = await axios.get(
updateURL
);
console.log('updateFetch', updateFetch);
if (updateFetch.data.enabled) {
const capApp = await App.getInfo();
const capAppVersion = capApp.version;
console.log('Thi is a thinkg', capAppVersion);
if (isPlatform('android')) {
console.log('hi');
const { currentAndroid, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentAndroid.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
} else {
const { currentIos, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentIos.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
}
}
} catch (err) {
console.log('Error in checkForUpdate', err);
}
}
}
For some reason, in my test I wrote to test this, my axiosSpy only shows that it has been called 1 time instead of the expected 2 times. The console logs I posted for both get requests run as well. I cannot figure out what I am doing wrong.
Here is the test:
it.only('should render the update page if the fetch call to update bucket is enabled and returns a different major version', async () => {
const isPlatformSpy = jest.spyOn(ionicReact, 'isPlatform');
isPlatformSpy.mockReturnValueOnce(true).mockReturnValueOnce(true);
const appSpy = jest.spyOn(App, 'getInfo');
appSpy.mockResolvedValueOnce({
version: '0.8.0',
name: 'test',
build: '123',
id: 'r132-132',
});
const axiosSpy = jest.spyOn(axios, 'get');
axiosSpy
.mockResolvedValueOnce({
data: {
enabled: false,
msg: {
title: 'App maintenance',
msg: 'We are currently solving an issue where users cannot open the app. This should be solved by end of day 12/31/2022! Thank you for your patience 😁',
btn: 'Ok',
type: 'maintenance',
},
},
})
.mockResolvedValueOnce({
data: {
current: '1.0.0',
currentAndroid: '1.0.0',
currentIos: '2.0.0',
enabled: true,
majorMsg: {
title: 'Important App update',
msg: 'Please update your app to the latest version to continue using it. If you are on iPhone, go to the app store and search MO Gas Tax Back to update your app. The button below does not work but will in the current update!',
btn: 'Download',
type: 'major',
},
minorMsg: {
title: 'App update available',
msg: "There's a new version available, would you like to get it now?",
btn: 'Download',
type: 'minor',
},
},
});
customRender(<UpdateChild />);
expect(axiosSpy).toHaveBeenCalledTimes(2);
});
I have a incoming state for controller that may be draft, published of something else, Right now I am handling these three functions separately, How can I combine them together, to form a more clear code
if (state === 'published') {
return this.checklistModelService.getAllWhere(
{ '$checklistRevision.publishedAt$': { [Op.ne]: null } },
undefined,
{
include: { model: ChecklistRevisionSchema },
},
);
}
if (state === 'draft') {
return this.checklistModelService.getAllWhere(
{ '$checklistRevision.publishedAt$': { [Op.is]: null } },
undefined,
{
include: { model: ChecklistRevisionSchema },
},
);
}
return this.checklistModelService.getAll(undefined, {
include: { model: ChecklistRevisionSchema },
});
You can do it in this way, first store the findOptions in a seperate variable and than use that in the query.
var findOptions = {};
state
? (findOptions = {
where: {
'$checklistRevision.publishedAt$': {
[state === 'published' ? Op.ne : Op.is]: null,
},
},
include: { model: ChecklistRevisionSchema },
})
: (findOptions = {
include: { model: ChecklistRevisionSchema },
});
return this.checklistModelService.getAll(undefined, findOptions);
I would like to store every arrivalDate in my array list.
Someone could tell me how can I do it?
But my array is still empty.
JSON returned by the API:
{
"reservations": {
"reservationInfo": [
{
"roomStay": {
"arrivalDate": "11am"
},
"WeatherR": {
"sound": "cloudy"
},
},
{
"roomStay": {
"arrivalDate": "7pm"
},
"WeatherR": {
"sound": "cloudy"
},
}
]
}
}
component.ts
searchForReservation() {
alert('hello');
this.http.get('/api/searchForReservation')
.subscribe((data) => {
this.ddataIno = data;
this.ddataIno = this.ddataIno.result.reservations.reservationInfo;
console.log('number of value', this.ddataIno.length);
console.log('content', this.ddataIno);
for (let i = 0; i <= this.ddataIno[i].length; i++) {
this.list = this.ddataIno.roomStay.arrivalDate;
}
console.log('store array', this.list)
})
}
searchForReservation() {
alert('hello');
this.http.get('/api/searchForReservation')
.subscribe((data) => {
const reservationInfo = this.data.result.reservations.reservationInfo;
this.list = reservationInfo.map(e => e.roomStay.arrivalDate);
})
}
Here's a working example in vanilla JS. You would need to make some small adjustments for angular, like this.list = ... instead of let list = ...
Using Array#map, you can create a new array from the JSON object
data.reservations.reservationInfo.map(r => r.roomStay.arrivalDate)
let data = {
"reservations": {
"reservationInfo": [{
"roomStay": {
"arrivalDate": "11am"
},
"WeatherR": {
"sound": "cloudy"
},
},
{
"roomStay": {
"arrivalDate": "7pm"
},
"WeatherR": {
"sound": "cloudy"
},
}
]
}
}
// declare your list as an array at the top
// list: []
// below would start off as 'this.list'
let list = data.reservations.reservationInfo.map(r => r.roomStay.arrivalDate);
console.log(list);
Your for loop is just reassigning the value of this.list
I suggest reading up on Array methods
I would use a map method, e.g.
this.list = this.ddataIno.result.reservations.reservationInfo.map(i => i.roomStay.arrivaldate);
Am new in Angular technology and working with Angular with spring boot as back end. Am stuck in reloading data gird.i have a backed API call for populating data gird. My issue was like some time data will change in the response.based on this I need to update my data grid in UI.
Edit 1
Angular.ts file
#ViewChild('modal', { static: false }) modal;
columns = [
{
prop: 'Name',
name: 'name'
},
{
prop: 'Location',
name: 'Location'
},
{
prop: 'Status',
name: 'Status'
}
];
ngOnInit() {
}
getData(name): Observable<Nodes> {
return this.service.getData(name).pipe(map((data) => {
return data;
}));
}
loadInitialData() {
this.getData(this.name).subscribe((data) => {
this.dataFrom = data;
this.service.saveMessage(data);
data.dataNodes.forEach((elm) => {
if (elm.archiveGroups === null) {
return;
}
elm.archiveGroups.forEach(arch => {
if (arch.archives === null) {
return;
}
let row: rowJson;
arch.archives.forEach(arc => {
row = Object.assign(new rowJson(), {
Name: arc.Name,
Location: elm.NodeName,
Status: arc.status,
});
this.rows.push(row)
});
});
});
this.loadingState = false;
this.populateData();
}, err => {
});
}
Edit 2
I have done below changes in ngOnInit method.but status filed not updated
ngOnInit() {
this.updateSubscription = interval(1000).subscribe(
(val) => {
this.getData(this.hostname).subscribe((data) => {
data.dataNodes.forEach((elm) => {
elm.archiveGroups.forEach(arch => {
if (arch.archives === null) {
return;
}
arch.archives.forEach(arc => {
let row: rowJson;
row.Status=arc.status
});
});
});
});
}
);
}
How to update status field based on getData API response.I could see a lot of queries regarding reload. Please guide and suggest a valid Solution
I want to check an Array until it's filled and show up a loading dialog but it always tells me
this.events[0] is undefined
ngOnInit() {
this.initMethod();
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
}
But events cant be undefined because it contains event of a calendar which get displayed.
initMethod() {
this.service
.getEmployees()
.subscribe(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
});
},
(err) => console.log(err)
);
}
}
And Constructor:
constructor(private modal: NgbModal, private service: BookingService, private dialog: MatDialog) {
this.initMethod();
this.dialog.open(DialogLaedt, {
width: '650px'
});
Your issue is that you initMethod() retrieves the result asynchronously.
So when you reach the line with if(this.events[0].start == ... there is no guarantee that the event data has been retrieved from the service yet.
The fix is to move your check inside the subscribe part of your init method (which executes as soon as the observable emits it's value), or let the init method return an observable that you can subscribe to, and perform your check inside that subscription.
Solution 1 - Moving your check inside subscription
ngOnInit() {
this.initMethod();
}
initMethod() {
this.service
.getEmployees()
.subscribe(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
});
},
(err) => console.log(err)
);
}
Solution 2 - Letting your initMethod return an Observable
ngOnInit() {
this.initMethod().subscribe(() => {
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
});
}
initMethod() {
return this.service
.getEmployees()
.pipe(tap(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
});
}))
}
I have noticed that you are calling the initMethod() twice. Once in the constructor, and once in the ngOninit method.