react-native re - ender component by clicking a button from another component - react-native

I have a list of interventions on my "first page". When I click on one, I navigate to its details, "second page", and there, is a button that allows me to start the events. When I click on that button it fills an object from a route : api/current
{
"interventionSummary": {some object}
}
When there's no intervention started :
{
"interventionSummary": null
}
When an intervention is started, it should be ended too so if the users doesn't I want to show a reminder message in the interventions list ("page 1") using: if interventionSummary !== null -> display the message to remind to end the intervention.
The problem is that my object interventionSummary is not updated when I go back on my interventionsList, unless I reload. For another page I was able to use :
this.props.navigation.addListener('focus', doStuff);
But the button and the route used were in the same page. I have tried, forceUpdate, simulate a state change : this.setState({state : this.state}) from solution on google, but nothing is working, I don't know how to make the component interventionsList see the update, or just re render after the click on the "second page"...
I hope that's clear, if anyone knows a way to do that

in your first page create your function.
myMethod() {
//function i want to call in second page
}
in your first page when navigating to second page(in my case when user presses a button) pass a function as a parameter like below:
onPress={() => this.props.navigation.navigate('SecondPage', {
rerenderOutputTitles: () => this.myMethod(),
})}
then in second page call this method wherever you want like below:
this.props.navigation.state.params.rerenderOutputTitles();

Related

Vue.js - How to load data with method call via click and toggle data?

I'm loading data via my rest api when the button is clicked with a vue.js method. To hide the loaded data I'm clicking the button again. When I'm clicking the button to show the data again, the same method is called again and the data is shown twice.
<div v-if="comment.answers_count !== 0">
<button
#click="toggleAnswers"
:class="{
'btn-danger': loadAnswers,
'btn-outline-danger': !loadAnswers
}"><strong>{{ comment.answers_count }} show answers</strong></button>
</div>
How can I load the data once, hide it with button clicked and show the same loaded data when toggling the button?
Maybe theres a way to use a computed property?
Create a new property in data:function(){}
e.x
data:function(){
answers_loaded:false
}
then on your function toggleAnswers
do the following
methods:{
toggleAnswers:function(){
/** if answers are not loaded , load them **/
if(!this.answers_loaded){
/** mark answers_loaded to true, so we do not call this code
again. Should be better put on your success request handler
to make sure that they were successfully loaded**/
this.answers_loaded = true;
//code to load the answers
}
}
}
So the first time that you click the button and function toggleAnswers is called the variable answers_loaded pass the if check.
Every other time that you click the button since answers_loaded is equal to true, it will fail the if check and wont call again part of the code to load the answers
So,i can't get you real purpose?
if you want to just load data once, you can use v-once, eg
<button #click.once="loadData" #click="hideData"> loadData or hideData</button>
...
loadData() {
setTimeout(() => {
this.data = 'loaded data'
}, 500)
},
hideData() {
this.data = this.data && null
}
if you want the toggle circle then you should set a tag using %2 to judge which function to run .

Why Is Vue Data Element Changing When I Only Set It Once?

I have created a component that allows users to select objects from a list and put them into another "selected list" lets say. So there are 100 items in the main list and however many in the users selected list. They can of course remove and add items as they want.
There are two buttons at the bottom of the modal. Cancel and Update. Where Cancel forgets anything they have added or removed (essentially an Undo of when they popped up the modal) and Update technically does nothing because when you are adding and removing, I am actually updating the real selected list.
So my data has these two properties (among others of course):
originalSelections: [],
selectedMedications: [],
There is a method that only gets called one time to set the selectedMedications property to whatever the current state of originalSelections is. I have a console.log to prove I am not running this method more than once and it NEVER gets hit again.
console.log('Post Initing');
let Selected = [];
for (let med of this.value.OtherNotFromEpic) {
let match = this.otherMedications.find(x => { return x.value === med });
if (match) {
Selected.push(JSON.parse(JSON.stringify(match)));
this.originalSelections.push(JSON.parse(JSON.stringify(match)));
this.selectedMedications.push(JSON.parse(JSON.stringify(match)));
}
}
I was baffled at why the selectedMedications was changing, so I added a watch to let me know if it was:
watch: {
originalSelections(newValue) {
console.log(' ** Original Selection Changed', this.init, newValue);
},
},
The Cancel method is as follows:
cancel() {
$('#' + this.modalID).modal('hide');
console.log('Cancel: this.originalSelections', JSON.parse(JSON.stringify(this.originalSelections)));
this.selectedMedications = this.originalSelections;
this.$nextTick(() => {
console.log(' Cancelled: this.selectedMedications', JSON.parse(JSON.stringify(this.selectedMedications)));
});
},
You can see that I am setting selectedMedications to whatever it was originally.
The odd thing is... This WORKS 100% the first time I bring up the modal. So I pop up the modal, remove an item, cancel the modal and it brings back the item I removed. Perfect!
If I bring the modal up again, remove that same item or any other item, cancel the modal and that item stays removed and the watch is actually hit. I have NO other place in the code where originalMedications = … or originalMedications.push or even originalMedications.slice ever happen. And it is my understand that the JSON.parse(JSON.stringify(match)) code I use to set it is making a new object and not a reference in any way.
Another odd thing I have found is that if I refresh the page, open the modal, cancel out without doing any adding or removing. Then I bring up the modal again and try either add or remove, then cancel the modal, those items do not revert back to the originalMedications state because originalMedications is the same as selectedMedications. Aargh!
So HOW can a property get altered when I never do anything to it after the initial setting of it?
In the cancel method, when below direct assignment is done here after both data is referring to same (since its array). So any time after the first cancel both originalSelections and selectedMedications array would have same reference and hence same data.
this.selectedMedications = this.originalSelections;
instead better to use concat as below? This will create a copy of originalSelections and assign that to selectedMedications. So any operations on selectedMedications will not affect the originalSelections.
this.selectedMedications = [].concat(this.originalSelections);

How to reuse data between routes in Aurelia?

I have an user entity in the system and the following route fetches it from server and displays its details:
routerConfiguration.map([
// ...
{route: 'user/:id', name: 'user-details', moduleId: './user-details'}
]);
Now I want to display an edit form for the displayed user. I have the following requirements:
Edit form should have a separate URL address, so it can be sent to others easily.
When user clicks the Edit button on the user's details page, the edit form should use an already loaded instance of the user (i.e. it should not contact the API again for user details).
When user clicks the Edit button on the user's details page and then the Back button in the browser, he should see the details page without edit form again.
1st attempt
I tried to define the edit form as a separate page:
routerConfiguration.map([
// ...
{route: 'user/:id/edit', name: 'user-edit', moduleId: './user-edit'}
]);
This passes the #1 and #3 requirement but it has to load the user again when the edit form is opened.
I don't know any way to smuggle some custom data between the routes. It would be perfect if I could pass the preloaded user instance to the edit route and the edit component would use it or load a new one if it is not given (e.g. user accesses the URL directly). I have only found how to pass strings to the routes in a slighlty hacky way.
2nd attempt
I decided to display the edit form in a modal and show it automatically when there is a ?action=edit GET parameter. The code inspired by this and this question:
export class UserDetails {
// constructor
activate(params, routeConfig) {
this.user = /* fetch user */;
this.editModalVisible = params.action == 'edit';
}
}
and when the user clicks the Edit button, the following code is executed:
displayEditForm() {
this.router.navigateToRoute('user/details', {id: this.user.id, action: 'edit'});
this.editModalVisible = true;
}
This passes #1 (the edit url is user/123?action=edit) and #2 (the user instance is loaded only once). However, when user clicks the Back browser button, the URL changes as desired from user/123?action=edit to user/123 but I have no idea how to detect it and hide the edit form (the activate method is not called again). Therefore, this solution fails the #3 requirement.
EDIT:
In fact, I have found that I can detect the URL change and hide the edit form with event aggregator:
ea.subscribe("router:navigation:success",
(event) => this.editModalVisible = event.instruction.queryParams.action == 'edit');
But still, I want to know if there is a better way to achieve this.
The question is
How to cope with this situation in a clean and intuitive way?
How about adding a User class that will serve as the model and use dependency injection to use it in your view-models?
export class User {
currentUserId = 0;
userData = null;
retrieve(userId) {
if (userId !== this.currentUserId) {
retrieve the user data from the server;
place it into this.userData;
}
return this.userData;
}
}

set jqGrid page before url is called

I am looking for a way to set the page of a jqGrid to x...
My use case is someone is using my grid...
They click on a patient to edit that patient (I am not using jqGrids modal edit screen... to many modal windows already)...
When the save what they did to that patient, I want to redirect the browser back to the screen where they clicked on that patient, and back to the SAME PAGE...
The thing to keep in mind.
I am using asp.net MVC4. I call the first page via an action method. The url variable of my grid is another action in the same controller. That action is what I send my page and row variables down to. I am sure that this can be done, However, I have no idea of how to achieve it. So far I have tried to set the page variable and rows variable in my document.ready before I call the jqGrid...
tbl.jqGrid({
loadBeforeSend: function () {
page: pageFromTemp;
rows: rowFromTemp
}
});
basically I have tried different ways to do it. The above is just one of them.
I have tried to reload the grid in the document.ready. But that doesn't make any sense. Why reload the grid when you haven't given it any of the parameters it needs...
I have tried to set the variable in the beforeRequest event. I have a function that I try and set it in...
beforeRequest: function () {
if ((rowFromTemp != "") && (pageFromTemp != "")) {
$(this).trigger('reloadGrid', [{ page: pageFromTemp, rowNum: rowFromTemp, url: '/Encounters/GetAjaxPagedGridData/' }]);
//$.extend($(this).setGridParam({ page: pageFromTemp })),
//$.extend($(this).setGridParam({ rowNum: rowFromTemp })),
//$.extend($(this).setGridParam({ url: '/Encounters/GetAjaxPagedGridData/' }))
//$.trigger('reloadGrid', [{ page: pageFromTemp, rowNum: rowFromTemp, url: '/Encounters/GetAjaxPagedGridData/'}]);
}
},
But that doesn't work either. I am obviously missing something. What am I doing wrong...
Got it to change to the right page using loadComplete and $("frTable").trigger({})
But now I am getting a flashing Loading screen which indicates to me that it is still loading the data...
If I set a breakpoint in my code, I can confirm that it is loading the data. I am not doing something right here.
Load the grid in document ready, have it's datatype set to local, have it's url unassigned, and have it hidden. When you want to have it load, trigger the load after setting the parameters and then show it to the user.

Back button on first level of nestedlist

I have a nestedList with a few levels that appears when the user presses a button on the screen. When the nestedList appears, there is no back button (because we're at the top of the tree, so understandably there is nowhere to go back to), whereas tapping on items in the list takes you to screens with a back button.
I'd like to add a back button to the first screen. I have managed to do this, but not without adding the same back button to every sublist in the nestedList - this has the effect of 1 back button at the top level, and 2 back buttons (one to take you out of the nestledList completely, and one to take you up a level) at every subsequent level.
Can anyone help me figure out how to have 1 back button on each screen, including the top level to close the list?
Many thanks
PS a nasty workaround that I'm using at the moment is to have a "close" button in the top right of every screen instead.
I don't know how comfortable you are with the inner workings of Sencha Touch so how you go about doing this is up to you--
The back button is there, hidden, when the nested list is shown (created in the initComponent function with hidden: true), and then onBackTap, onItemTap and setActivePath will all call syncToolbar near the end of their functions which is where the back button is hidden when you are at a depth of 0.
So there are 2 places you need to do something about, first is initComponent which is easy-- just implement initComponent in your nestedList, call the superclass' initComponent and then set the backButton visible
var myNestedList = new Ext.NestedList({
...,
initComponent: function() {
myNestedList.superclass.initComponent.call(this);
this.backButton.setVisible(true);
},
...
});
That takes care of showing it intially.. how you care to deal with fixing syncToolbar is up to you. You can use Ext.override, you can straight up copy and paste the whole syncToolbar function into your nestedList object which would also override it or you could do what you're told never to do and just edit the sencha-touch.js file directly. However you decide to do it, what you're looking to change is
syncToolbar: function(card) {
...
backToggleMth = (depth !== 0) ? 'show' : 'hide';
if (backBtn) {
backBtn[backToggleMth]();
if (parentNode) {
backBtn.setText(backBtnText);
}
}
... };
You can either change backToggleMth to = 'show' or just delete the if (backBtn {...} all together.
In the Sencha Touch 2.2 I had to use a different code:
Ext.create('Ext.NestedList', {
...,
listeners: {
initialize: function(obj) {
obj.getBackButton().show();
},
back: function(obj, node, lastActiveList, detailCardActive) {
switch(node.getDepth()) {
case 1:
obj.getBackButton().show();
break;
case 0:
alert("wohooooooo!");
break;
}
}
}
}