Trying to set a analyzed state when a variable has finished analyzing - javascript

I am working on a react project. I have made some changes to the way we render content to a screen and am now having a problem finding a solution.
I have a variable that returns text dependent on its content. If the variable is empty, which is its default state, we say that no data was found. If we have some data we render the data. The problem is, that I need to set a default value to the variable so it does not show no data was found when it is analyzing.
I have tried using state to set a analyzed flag but can't seem to get it to work?
So for example:
let filterWhatToShowUser =
// here we filter through the data and determine what the result of filterWhatToShowUser is shown to the user
);
JSX
if there is data ?
<div>Show this</div>
:
<div>Show this when the object is empty</div>
:
<div>Show this whilst the object is empty but evaluating</div>

if(data) => show data
if(!data && ! evaluating) show something
show something else
ternary operator is about "if & else", no need to make complex constructions out of them

Related

Angular 6 template doesn't update when variable changes

I have a menu object that will end up displaying a menu on the template. One of the menu objects properties is set by a variable that gets changed during the ngOnInit(). At that point, the template is already created I believe, so the menu never updates.
We want the MemberProfile link to display the user ID and not the 'undefined' that it is initialized with.
Check out the stack blitz link.
It's pretty straight forward I know I'm missing something simple.
When you open the menu, I'm printing out the Link Label and the Link URL.
The second link should be Admin/MemberProfile/45 and not Admin/MemberProfile/undefined
https://stackblitz.com/edit/angular-ivy-yu9hty
First, you need to understand how template/html rendering in Angular works.
As in your case, since you are rendering your menu link list from an array, menu.admin. Angular will not re-render the *ngFor block, until it detects changes in the menu.admin array. So, you just need to update that array.
Now, what you can do is something like this,
public ngOnInit() {
this.userId = 45;
this.menu.admin[this.menu.admin.length - 1].link = '/Admin/MemberProfile/' + this.userId
}
For more info please refer to Angular lifecycle hooks.
When the property menu is declared and assigned a value, this expression
'/Admin/MemberProfile/' + this.userId
is evaluated, using the then-current value of userId. When you do
this.userId = 45;
the value of menu isn't computed again.
There are several possible solutions. Put the menu layout in the template, instead of the TS (and use {{ userId }} there), use RxJS to update the thing dynamically, or simply imperatively recalculate the value of menu when changing userId (the most crude solution, and requiring the least amount of writing on my part), shown here:
https://stackblitz.com/edit/angular-ivy-qpnaqz?file=src/app/app.component.ts
Player's choice.

React.js - Can't access an element's value in an Array of Objects

I feel like a lousy developper coming to you with that question but I'm going in circles.
I'm using React/JS and here's the problem :
The code imports an array of objects from my personnal API via ajax (axios).
My state expect an array : const [ films, setFilms ] = useState([]); and receives one.
Indeed, the response.result from my API is an array of 20 movie objects :
I just want to pass it as props to another component in which I'm gonna use one of the object stored in the array to use and display its values but I've been unable to do so...so far.
Now, in React, when I test to call one movie like this :
console.log("films", films); => WORKS (shows screen capture above),
console.log("film", films[0]); => WORKS (shows first element, an object),
But if I try to enter it (any properties) :
console.log("film", films[0].id); OR console.log("film", films[0]["id"]);
=> FAILS : TypeError: films[0] is undefined !
I know I'm missing something. I receive an array of object, can enter an element but can't read its properties...
I feel lost... Help ? :)
Thank you
Probably your console.log("films", films); method is called a couple of times even films are not loaded yet. When you try to log films it will first log null or an empty array, but then it will show the correct list. On the other hand, when you have console.log("film", films[0].id);, your app will crash because it was called while films array is null or empty.
So make sure that your film array length is greater than 0 before logging.
try using the && operator like this :
console.log("film", films[0] && films[0].id);

activating checkbox on load with javascript or jQuery

hello I have a small project I'm working on.
the project is calling an API with ajax and getting info about currencies, one of the things I'm stuck on is that I have to write them in cards that include a checkbox that has to stay activated after I refresh the page.
any suggestions?.. please I'm desperate
When you make your call on your API just set the checked value on the correct checkbox, please have in mind that setting checked=false will still give you a checked checkbox.
<input type="checkbox" checked>
One way to preserve information against a page refresh is to use localStorage.
LocalStorage allows you to store key:value variable pairs in the local browser. You can view the localStorage values for any given website in DevTools F12, on the Application tab. The variables are stored by website, and remain as they are until (a) they are deleted, or (b) browser cache is cleared. (For more info on when localStorage is cleared, see this answer).
LocalStorage is dead-simple to use:
let myPet = 'Cat';
localStorage.setItem('animal', myPet);
And to read it:
let myPet = localStorage.getItem('animal');
What you might want to do in your project, perhaps on a timer - or after the ajax call - is loop through your fields and create an object with all the fieldnames/values. Then use JSON.stringify to turn the object into text that you can store in a localStorage variable.
Note that you will need to write something that on page load ( $(document).ready() ) will see if the fields are empty and if there is a RECENT localStorage variable (so, you might want to create second localStorage variable (you can have MANY) that has the last-updated datetime) then you read the JSON string into a javascript object and populate your field values.
I would recommend using a dictionary, putting something unique like an ID of those currencies that are checked at that time.
If the new answer you get has the same currencies as before plus more, you can use that dictionary in memory to check those items again. If you don't get the previous response, you can just add those new items to avoid unchecking the checked currencies.
Exmaple:
var dictionary = {};
// here you should do a forEach in currently checked currencies
...
dictionary[id] = value; // (true, because it is the value of checked)
Hope it helps you.

AngularJS - NgOptions from function returning undefined values

I've got an application which has to show some options inside a select depending on a previous option. To achieve this, I've put the logic to show those options inside a controller function, like this:
vm.getScopeValues = function(tp){
var vals = [];
vals.push({n: 'Opt1', v: 'opt1'});
if(!tp || tp != 'somevalue'){
vals.push({n: 'Opt2', v: 'opt2'});
}
return vals;
};
The problem is that sometimes, I get an undefined as the value of the select options. On the following jsFiddle you can see a simpler approach, but with same result:
https://jsfiddle.net/nr9ffrkk/
As you can see:
If I write track by v, I get undefined
If I write track by o.v, then the values are right, but the ng-model does not get matched correctly
If I write o.v as o.n... without the track by, I get an error ($digest cycles)
When everything gets matched correctly (I achieved it somehow but cannot remember how), if I add a new dynamic "field" (click on "ADD NEW FIELD"), then they come out as undefined values again
I've made console.log to watch the returning values of the function, and it gets called correctly and returns the right values (nothing undefined).
I need to be able to create dinamycally new entries on the fields array (with an initial value for type, of course) and that the select gets the right values for the options.
UPDATED
As you can see, making a controller variable (not a function) with the values does not work neither, bringing the same problem:
https://jsfiddle.net/dgy5ryvh/
Thank you!

How can I handle a potentially pre-filled form with Jade?

I have this huge form that only gets pre-filled data if data already exists in a database. Otherwise, none of the text boxes should have the value parameter in them. I thought it would just ignore the value parameters if the variable I get data from does not exist. But instead, I get an error.
How to I handle this case? Will I have to do an if check before each text box in Jade like the following?
if (typeof(prefilled_data) !== 'undefined')
input.form-control#prevalence(type="text", name="prevalence")
else
input.form-control#prevalence(type="text", name="prevalence", value=prefilled_data.tb_burden_estimates.prevalence)
While I don't mind doing this (Sublime Text will help with all the copy-pasting), there are quite a few form fields, so it might get ugly. Is there a way to consolidate this into one check somewhere?
you seemed to be suggesting that the if statement's were going to be bulky/make the code hard to read if they were there.. my suggestion would be to programmatically create the inputs, there by reducing the if statements to a more manageable number and answering your question about being able to "consolidate this into one check somewhere"
EDIT
If you are looking to access data in js.. I have been known to use something like:
script(type='text/javascript').
window.prefilled_data = !{ JSON.stringify(prefilled_data) };
This will allow you then to access the global window.prefilled_data variable to get front end version of your data
you can do this:
- if (typeof(prefilled_data) === 'undefined'){
- prefilled_data = '';
- }
input.form-control#prevalence(type="text", value=#{prefilled_data})
if prefilled_data is undefined you just set a '' value

Categories