my component is not re-rendering on state change react native - react-native

this is my declaration of state :
state = {
shouldShow1: Boolean = false,
shouldShow2: Boolean = false,
shouldShow3: Boolean = false,
shouldShow4: Boolean = false,
shouldShow5: Boolean = false,
shouldShow6: Boolean = false,
shouldShow7: Boolean = false,
shouldShow8: Boolean = false,
shouldShow9: Boolean = false,
};
then i change the value of one state each time the user click on button
if (this.state.shouldShow1 == false) {
this.state.shouldShow1 = await true;
this.state.shouldShow2 = false;
this.state.shouldShow3 = false;
this.state.shouldShow4 = false;
this.state.shouldShow5 = false;
this.state.shouldShow6 = false;
this.state.shouldShow7 = false;
this.state.shouldShow8 = false;
this.state.shouldShow9 = false;
.............
and i have a code like this in the render
return(
{this.state.shouldShow1 == true ? Show View A : Show View B }
{this.state.shouldShow2 == true ? Show View A : Show View B }
)

Bernhard Josephus answered resolved my problem the solution is :
i should have used this.setState({ shouldShow1: true, shouldShow2: true, .... })
instead of just affecting values.

Related

How can I retrieve value from api and set to variable to enable or disble the button

const getConfig = (Id : string) => {
const configTypeCode = "MANUAL-ENABLED"
let isEnableManual = false;
configApi.getConfig(id, configTypeCode).then(response => {
console.log("11111",response);
if(response.body.value === 'true'){
isEnableManual = true;
console.log("2222",isEnableManual);
return isEnableManual;
}
});
return isEnableManual;
I want to enable disable the button if isEnableManual is true but I don't understand why isEnableManual always change to false, I want it to be the same as response from api How can I fix this.

Global Variables only Called Once then Lost their Scope

I Have a Problem with my Script and hope helping me, and thanks in advance, i still learning javascript and try to learn somthing new everyday, i have a script that draw modeless interface (palette) and have button including (option) that make another new palette (for options), i made the variables as globals for the option palette, but the problem is the global variables is only called once!, and the script lose the global variable scope!.
enter image description here
so my question is how to make the variables not losing its scope and retain in the memory? as long the script run, as an Example if the user move the slider and hit (Show alert due options) its only run once and then lose the scope, even the slider no longer interact with the user and update text box, please test the code to see the problem, and thank again for any help or advice.
Best
M.Hasanain
//Global Variables only Called Once then Lost their Scope!
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if (app.documents.length > 0) {
var myDoc = app.activeDocument;
}else{
// No documents are open, so display an error message.
alert("No InDesign documents are open. Please open a document and try again.");
}
}
//---------------------------------------------------------
//Making Palettes Windows
//---------------------------------------------------------
#targetengine "session1";
var w = new Window("palette", {independent:true}); //Main Palette Windows
var findoptions = new Window("palette"); //Options Palette
//gqmanager is the (GREP Query Manager) outside the main Function
w.text = "Test the Connection Between Global Variables and Palettes";
w.preferredSize.width = 500;
w.alignChildren = ["center", "center"]; //"left";
w.orientation = "column"; //"row";
w.spacing = 10;
w.margins = 16;
//Parent - Input Panel Prepare
var InputPanel = w.add("panel", undefined, undefined, { name: "panel1" });
InputPanel.text = "Text Find : ";
InputPanel.preferredSize.width = 1000;
InputPanel.orientation = "row";
InputPanel.alignChildren = ["center", "center"];
InputPanel.spacing = 10;
InputPanel.margins = 16;
//Children - input Panel Inside Prepare
var myInputPanelInside = InputPanel.add("group", undefined, { name: "myInput" });
//--Adding Find What
myInputPanelInside.add("statictext", undefined, "Find What :");
//myInputPanelInside.alignment = "center";
var myGREPString = myInputPanelInside.add("edittext", undefined, "SAMPLE");
myGREPString.helpTip = "Enter Your Text"
myGREPString.characters = 20;
myGREPString.enabled = true;
myGREPString.preferredSize.width = 460;
var Button1 = myInputPanelInside.add("button", undefined, "Options");
//Parent - Radio Panel Prepare
var RadioPanel = w.add("panel", undefined, undefined, { name: "panel2" });
RadioPanel.text = "Select Desired Option : ";
RadioPanel.preferredSize.width = 1000;
RadioPanel.orientation = "row";
RadioPanel.alignChildren = ["center", "center"];
RadioPanel.spacing = 10;
RadioPanel.margins = 16;
//Children - input Panel Inside Prepare
var myRadioPanelInside = RadioPanel.add("group", undefined, { name: "myRadio" });
myRadioPanelInside.preferredSize.width = 500;
myRadioPanelInside.alignChildren = ["center", "center"];
//Adding Radio Buttons
var radio1 = myRadioPanelInside.add("radiobutton", undefined, "Option 1");
var radio2 = myRadioPanelInside.add("radiobutton", undefined, "Option 2");
var radio3 = myRadioPanelInside.add("radiobutton", undefined, "Option 3");
radio1.preferredSize.width = 200;
radio2.preferredSize.width = 200;
radio3.preferredSize.width = 200;
//Previous Default Condition
radio1.value = true;
var myButtonGroup = w.add("group");
myButtonGroup.alignment = "center";
var Button2 = myButtonGroup.add("button", undefined, "Show Alert Due Options");
var Button3 = myButtonGroup.add("button", undefined, "Exit");
Button1.onClick = function () {
CalltheFindOptions();
}
Button2.onClick = function () { Find(); };
function Find() {
doRadioButtonOpt();
}
Button3.onClick = function() {Canceled();};
function Canceled() {
ExitSure();
}
//After Drawing Interface
var a = w.show();
function ExitSure() {
var a = w.close();
exit(0);
}
//User Selection for Radio Buttons
function doRadioButtonOpt() {
myDoc = app.activeDocument;
if (radio1.value == true) {
TestVars();
}
}
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText.text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults.value == true) { //no Show only Apply
alert("you Select not to Show Results!");
}else{ //Direct Show and Apply
if (ShowResultsDirect.value == true) {
alert("you Select to Show Results in real time!");
}else{ //Show and Apply By WaitinhTime!
if (ShowResults.value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
var DontShowResults;
var ShowResultsDirect;
var ShowResults;
var SliderControlText;
var slider;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, { name: "panel1" });
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
mySelectPanelInside = SelectPanel.add("group", undefined, { name: "mySelOpt" });
DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = true; //by Default
DontShowResults.alignment = "left";
ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = false; //by Default
//Adding Slider to Control MS Time
SliderControlText = mySelectPanelInside.add ("edittext", undefined, 10, {readonly: false}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
slider = mySelectPanelInside.add ("slider {minvalue: 1, maxvalue: 100, value: 10}");
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {SliderControlText.text = slider.value;} //Listen to Slider
var c = findoptions.show();
}
If I understand you correctly you need to use as global variables values rather than the objects. And you can change the values of global variables by onClick events.
Here is the bottom part of your code (the rest part of the code wasn't changed):
...
function TestVars() {
#targetengine "session1";
var myDoc = app.activeDocument
var TimeMs = Number(SliderControlText_text); //Converting Text to Number
//Show Results Found as User Wish
if (DontShowResults_value == true) { //no Show only Apply
alert("you Select not to Show Results!");
} else { //Direct Show and Apply
if (ShowResultsDirect_value == true) {
alert("you Select to Show Results in real time!");
} else { //Show and Apply By WaitinhTime!
if (ShowResults_value == true) { //Show and Apply
alert("you Select to Show Results with Specific time!");
$.sleep(TimeMs); //Wait ms
}
}
}
alert("Do you need somthing else?, try again", "Finish Report");
}
// values! not objects
var DontShowResults_value = true;
var ShowResultsDirect_value = false;
var ShowResults_value = false;
var SliderControlText_text = '10';
var slider_value = 10;
//--------------------------------------------Building the Find Options Palette-----------------------------------------//
//--------------------------------------------------------------------------------------------------------------------------------//
function CalltheFindOptions() {
#targetengine "session1";
//Find Options Window
findoptions.text = "Find Options";
//Parent - Input Panel Prepare
SelectPanel = findoptions.add("panel", undefined, undefined, {
name: "panel1"
});
SelectPanel.text = " Find Options : ";
SelectPanel.preferredSize.width = 1000;
SelectPanel.orientation = "row";
SelectPanel.alignChildren = ["center", "center"];
SelectPanel.spacing = 10;
SelectPanel.margins = 16;
//Children - input Panel Inside Prepare
var mySelectPanelInside = SelectPanel.add("group", undefined, {
name: "mySelOpt"
});
var DontShowResults = mySelectPanelInside.add("checkbox", undefined, "Don't Show Results");
DontShowResults.value = DontShowResults_value; //by Default
DontShowResults.alignment = "left";
// change the global variable by click
DontShowResults.onClick = function() { DontShowResults_value = DontShowResults.value }
var ShowResultsDirect = mySelectPanelInside.add("checkbox", undefined, "Show Results");
ShowResultsDirect.value = false; //by Default
// change the global variable by click
ShowResultsDirect.onClick = function() { ShowResultsDirect_value = ShowResultsDirect.value }
var ShowResults = mySelectPanelInside.add("checkbox", undefined, "Show Results Delayed in milliseconds(Ms) :");
ShowResults.value = ShowResults_value; //by Default
// change the global variable by click
ShowResults.onClick = function() { ShowResults_value = ShowResults.value }
//Adding Slider to Control MS Time
// SliderControlText = mySelectPanelInside.add("edittext", undefined, 10, {
var SliderControlText = mySelectPanelInside.add("edittext", undefined, SliderControlText_text, {
readonly: false
}); //read only prevent user Entering Nums
SliderControlText.characters = 3;
var slider = mySelectPanelInside.add("slider {minvalue: 1, maxvalue: 100, value: 10}");
// change slider every time as numbers is changes
SliderControlText.onChanging = function() {slider.value = SliderControlText.text};
//Slider Listener Plus SliderControl Text Listener
slider.onChanging = function () {
SliderControlText.text = slider.value;
// change the global variable by onChange
SliderControlText_text = SliderControlText.text;
} //Listen to Slider
findoptions.show();
}
It seems it works as intended.
As far as I can tell (I can be wrong), the cause of the problem was that the objects ShowResultsDirect, ShowResultsDirect, etc, disappears as soon as you close the palette. Because they are elements of the palette. They can't keep values if the palette is closed. That why they worked well only when you open the palette first time.

VueDraggable of Sortable is not working properly and send the choosed item to the first on init

I'm using Vue.Draggable in my Nuxt project. i used it in some pages and component and every thing is fine. but on one of my pages it gives me a silly problem!! when page is loaded, it send the chosen item to the first!! after that every thing works fine! even if i choose and unchoose without moving, things works fine!!
i tried to check if the choosed went to first of array move it again properly. it worked when the chosen item is the first if array but if i choose others than first, on 2nd try it move another item too!!
so i'm kinda stuck.
here is the code:
btw there are some variables and methods that u cant find them like cmsListItems. they are globally added to my project
template:
<draggable v-model="myItemsArray" #end="onEnd" #choose="onChoose" #unchoose="onUnChoose" v-bind="getOptions()">
<transition-group type="transition" name="sortable_transition">
<categorylistcard v-for="(category, index) in cmsListItems"
listtype="cat"
:key="category.id"
:cat="category"
:index="index"
:showforsub="showForSub"
:parentarr="parentArr"
#addnewsub="addNewCat()"
:sub="true"
:sublvl="true"
:sortable="true"
:btntitle="lang.addsubcat"
/>
</transition-group>
</draggable>
script:
export default {
data(){
return{
oldIndex: '',
newIndex: '',
dragOptions: {
ghostClass: "sortable_ghost",
chosenClass: "sortable_chosen",
handle: ".sortable_handle",
disabled: false
},
isMoved: false,
myItemsArray: [],
originalItemsArray: [],
choosedItem: null
}
},
methods:{
// ***** Reorder By Sorting *****\\
this.isMoved = true
this.oldIndex = event.oldIndex
this.newIndex = event.newIndex
console.log(this.myItemsArray[this.oldIndex])
console.log(this.myItemsArray[this.newIndex])
if(this.oldIndex !== this.newIndex){
this.dragOptions.disabled = true
let response = await this.axiosGet(`category/reorder/${this.originalItemsArray[this.oldIndex].id}/${this.originalItemsArray[this.newIndex].id}`)
if(this.resOk(response.status)){
this.noty(ALERT_TYPE[1], 'ok')
this.originalItemsArray = this.myItemsArray
this.isMoved = false
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
this.setCmsListItems(this.myItemsArray)
// this part is my defected solution
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
}
}, 50);
// --------------------
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
},
addClassToMovedItems(index){
if((index == this.oldIndex || index == this.newIndex) && this.isMoved == true){
return 'sortable_moved'
}else{
return ''
}
}
},
async fetch(){
this.btnLoading = true
let response = await this.axiosGet(`categories/admin/0/1`)
if(this.resOk(response.status)){
if(this.notEmpty(response.data)){
this.setCmsListItems(response.data.items)
this.myItemsArray = [...this.cmsListItems]
this.originalItemsArray = [...this.cmsListItems]
}
this.btnLoading = false
}
},
}
I kinda hacked through it, so i don't recommend it!!
I got the chosen item with #choose and in my #end checked if first index of my array is the chosen item, unshift array and add the chosen to newIndex with splice() like bellow:
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
this.choosedItem = null
}
}, 1);

VueJS & VUEX: Shortening JS Code

I love clean and simple code.
So I like to shorten these lines of javascript so they don't seem so cluttered.
My vuex-mutation code:
editEvent(state) {
if (
state.form.time !== '' &&
state.form.date !== '' &&
state.form.event !== '' &&
state.form.artist !== '' &&
state.form.organizer !== '' &&
state.form.location !== ''
) {
const event = {
time: state.form.time,
date: state.form.date,
event: state.form.event,
artist: state.form.artist,
organizer: state.form.organizer,
location: state.form.location
}
events.child(state.currentEventKey).update(event)
state.form.time = ''
state.form.date = ''
state.form.event = ''
state.form.artist = ''
state.form.organizer = ''
state.form.location = ''
state.currentEventKey = null
state.showForm = false
}
}
and here another one:
populateEventForm(state, payload) {
state.form.time = payload.event.time
state.form.date = payload.event.date
state.form.event = payload.event.event
state.form.artist = payload.event.artist
state.form.organizer = payload.event.organizer
state.form.location = payload.event.location
state.currentEventKey = payload.key
state.showForm = true
}
How can I improve this ?!??!
This is pseudo code for the most part. Somewhere store your common properties.
const props = ["time", "date", "event", "artist", "organizer", "location"]
Then use that in your functions.
function editEvent(state) {
// check to see if every property exists on the state
if (!props.every(p => state.form[p] !== '')) return
// build the event object
const event = props.reduce((acc, p) => acc[p] = state.form[p], {})
// I don't know where "events" comes from-- I left this alone
events.child(state.currentEventKey).update(event)
// clear each property
props.forEach(p => state.form[p] = '')
// clear your misc. props
state.currentEventKey = null
state.showForm = false
}
function populateEventForm(state, payload) {
props.forEach(p => state.form[p] = payload.event[p])
state.currentEventKey = payload.key
state.showForm = true
}
Please be advised, since you posted this as a Vue/Vuex question, you may need to use Vue.set instead of an indexer in cases like the event object being built. It's hard for me to tell from the limited code you posted. In that case it would be something like
const event = props.reduce((acc, p) => {
Vue.set(acc, p, state.form[p])
return acc
}, {})

CommonJS module in Titanium doesn't take callbacks

I have a QRcode scanner CommonJS module in Titanium mobile that I would like to add success and cancel callbacks to.
However my functions are always undefined inside the module.
My module:
var scanner = null,
successCallback = null,
cancelHandler = null;
function AndroidScanner(allowRotation, displayedMessage, allowMenu, allowInstructions, useLED){
this.scanner = require("ti.barcode");
if(allowRotation)
this.scanner.allowRotation = allowRotation;
if(displayedMessage)
this.scanner.displayedMessage = displayedMessage;
if(allowMenu)
this.scanner.allowMenu = allowMenu;
if(allowInstructions)
this.scanner.allowInstructions = allowInstructions;
if(useLED)
this.scanner.useLED = useLED;
};
//successListener changes the event to a common one for iOS and Android
AndroidScanner.prototype.successListener = function(event) {
Ti.API.info("Successcallback get: "+JSON.stringify(this.successCallback));
this.successCallback({barcode: event.result});
};
//Starts the scanner, pass the view to add the scanner to
AndroidScanner.prototype.startScanning = function(view) {
this.scanner.addEventListener('success', this.successListener);
this.scanner.addEventListener('cancel', this.cancelHandler);
this.scanner.capture({
animate : true,
overlay : null,
showCancel : true,
showRectangle : true,
keepOpen : false
});
};
//Removes event listeners from the scanner
AndroidScanner.prototype.stopScanning = function() {
this.scanner.removeEventListener('success', this.successHandler);
this.scanner.removeEventListener('cancel', this.cancelHandler);
};
//Add a success handler
AndroidScanner.prototype.successHandler = function(handler) {
Ti.API.info("Successhandler set: "+JSON.stringify(handler));
this.successCallback = handler;
};
//Add a cancel handler
AndroidScanner.prototype.cancelHandler = function(handler) {
Ti.API.info("Cancelhandler set: "+JSON.stringify(handler));
this.cancelHandler = handler;
};
module.exports = AndroidScanner;
In alloy.js:
if(OS_ANDROID) {
var AndroidScanner = require("/ui/AndroidScanner");
Alloy.Globals.scanner = new AndroidScanner(
true,
'',
false,
false,
false
);
}
Alloy.Globals.scanner.successHandler(function(e) {
Alloy.Globals.barcodeScannerOn = false;
//on successful scanning we know that windows is back
Alloy.Globals.barcodeScanSuccesfull = true;
Alloy.Globals.barcodeScanCanceled = false;
Alloy.Globals.scanner.stopScanning();
Alloy.Globals.barcodeScanResult = e.barcode;
Ti.API.info('scan result' + JSON.stringify(Alloy.Globals.barcodeScanResult));
});
Alloy.Globals.scanner.cancelHandler(function(e) {
Alloy.Globals.barcodeScannerOn = false;
Alloy.Globals.barcodeScanCanceled = true;
Alloy.Globals.barcodeScanSuccesfull = false;
Alloy.Globals.scanner.stopScanning();
});
The log always shows:
[INFO] : Successhandler set: undefined
[INFO] : Cancelhandler set: undefined
Any ideas why this is?