Reload a Data Grid based on back end API response Angular - angularjs

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

Related

Axios Spy not being called correct number of times in Jest

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

Create and update inside map function

I'm trying to find the right way to create and consequently update inside a map function.
These are the steps I need:
Map function "reads" the array of elements ids
Create new record on "leads_status" table
Using the new record id (from "leads_status") "leads" table is updated using "leads_status.id" as foreign key related to "leads.id_ls"
This is the code I tried.
const [create, { isLoading: isLoadingCreate, error: errorCreate }] = useCreate();
const [record, setRecord] = React.useState(null);
leadsIDS.map((value, index) => {
create('leads_status', {
data: {
id_lead: value,
id_status: 5
}
}, {
onSuccess: ({ id }) => {
setRecord([id, value]);
},
onError: () => {
console.log();
}
});
update('leads', {
id: record[1],
data: {
id_ls: record[0]
}
}, {
enabled: !isLoadingCreate && record !== null
}, {
onSuccess: () => {
console.log(record);
},
onError: error => notify('Error', { type: 'warning' })
})
})
I tried also to put the "update" function inside the "create --> onSuccess" but also there the code is not working as I want.
In "leads_status" table records are always created for each element in "leadsIDS" array but in "leads" table only 1 records is updating.
Where am I wrong?
The useCreate and useUpdate hooks are designed for single actions. If you want to chain several actions, I suggest you use the useDataProvider hook, instead, which lets you manipulate Promises.
const dataProvider = useDataProvider();
const notify = useNotify();
try {
await Promise.all(leadsIDS.map(async (value, index) => {
const { data: leadStatus } = await dataProvider.create('leads_status', {
data: {
id_lead: value,
id_status: 5
}
});
await dataProvider.update('leads', {
id: value,
data: { id_ls: leadStatus.id }
});
}));
} catch (e) {
notify('Error', { type: 'warning' });
}

React-Apollo: Recommended way of subscribing to multiple events that doesn't require UI updates

So i want to subscribe to multiple events for the current logged user.
I've extracted the subscriptions to a separate function that update my logged user state from inside and returns an array of subscriptions.
Now i wanted to know is there a different / better way of doing this ?
Is this the correct / recommended way of approaching this problem ?
Current implementation
export const subscribeToCurrentUserUpdates = (setLoggedUser) => {
const friendRequestObserver$ = apolloClient.subscribe(
{ query: queries.NEW_FRIEND_REQUEST },
);
const followersUpdatesObserver$ = apolloClient.subscribe(
{ query: queries.FOLLOWERS_UPDATES },
);
const acceptedFriendRequestObserver$ = apolloClient.subscribe(
{ query: queries.ACCEPTED_FRIEND_REQUEST },
);
const friendRequestSubscription = friendRequestObserver$.subscribe({
next: ({ data: { newFriendRequest } }) => {
Alert.success(`${newFriendRequest.username} just sent you a friend request`);
setLoggedUser((loggedUser) => {
loggedUser.incomingFriendRequests.unshift(newFriendRequest._id);
});
},
error: err => console.error(err),
});
const followersUpdatesSubscription = followersUpdatesObserver$.subscribe({
next: ({ data: { followersUpdates: { follower, isFollow } } }) => {
if (isFollow) {
Alert.success(`${follower.username} is now following you`);
}
setLoggedUser((loggedUser) => {
isFollow
? loggedUser.followers.unshift(follower._id)
: loggedUser.followers.splice(loggedUser.followers.indexOf(follower._id), 1);
});
},
error: err => console.error(err),
});
const acceptedFriendRequestSubscription = acceptedFriendRequestObserver$.subscribe({
next: ({ data: { acceptedFriendRequest: newFriend } }) => {
Alert.success(`${newFriend.username} just accepted your friend request!`);
setLoggedUser((loggedUser) => {
loggedUser.friends.push(newFriend._id);
loggedUser.sentFriendRequests.splice(
loggedUser.sentFriendRequests.indexOf(newFriend._id), 1,
);
});
},
error: err => console.error(err),
});
return [
friendRequestSubscription,
followersUpdatesSubscription,
acceptedFriendRequestSubscription,
];
};
The way i subscribe from my component
const App = () => {
const currentUserSubscriptionRef = useRef();
useEffect(() => {
if (loggedUser && !currentUserSubscriptionRef.current) {
currentUserSubscriptionRef.current = subscribeToCurrentUserUpdates(
setLoggedUser,
);
}
if (!loggedUser && currentUserSubscriptionRef.current) {
currentUserSubscriptionRef.current.forEach((subscription) => {
subscription.unsubscribe();
});
currentUserSubscriptionRef.current = null;
}
}, [loggedUser, setLoggedUser]);
}

Ionic 2: Add new array into array of objects

I would like to add an array into an array object. However, I am only able to add the array into a new object instead of the existing one. Is there any way where I can link the array to the existing object? Its much more easier for me too if I could add in the array based on which link it is from.
Here is my code:
this.af.database.list(`/users/${userid}/favourites`, {
query: { orderByChild: 'priority' },
preserveSnapshot: true
})
.subscribe(snapshots => {
snapshots.forEach(snapshot => {
this.category.push({
name: snapshot.val().name,
rss: snapshot.val().regions[0].rss
});
})
for (let i = 0; i < this.category.length; i++) {
this.http.get(this.category[i].rss)
.map(res => res.text())
.subscribe((data) => {
this.parseXML(data)
.then((data) => {
this.xmlItemsApac = data
this.category.push({
feeds: data
})
});
});
}
});
console.log(this.category)
parseXML(data) {
return new Promise(resolve => {
var k,
arr = [],
parser = new xml2js.Parser(
{
explicitArray: false
});
parser.parseString(data, function (err, result) {
var obj = result.rss.channel;
for (k in obj.item) {
var item = obj.item[k];
arr.push({
title: item.title,
link: item.link,
description: item.description,
pubDate: item.pubDate
});
}
resolve(arr);
});
});
}

Reflux listenAndPromise do action many times

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

Resources