React Native:object destructed return undefined - javascript

My React Native 0.62.2 destructing a props passed into a class within render () {}:
const {dataLen, img_source, width, ht, index, modalWidth, modalHt} = this.props;
Here is the console output of the props:
[Sat Aug 15 2020 17:42:19.350] LOG props in image disp : {"dataLen": 2, "ht": 352.8, "img_source": "file:///data/user/0/com.xyz_app2/cache/react-native-image-crop-picker/2.jpg", "index": 0, "modalHt": 780.1354401805869, "modalWidth": 360, "sortFn": [Function move], "width": 352.8} //<<== here is the value of props
[Sat Aug 15 2020 17:42:19.366] LOG object
[Sat Aug 15 2020 17:42:19.367] LOG ani code
[Sat Aug 15 2020 17:42:19.455] LOG props in image disp : {"dataLen": 2, "ht": 352.8, "img_source": "file:///data/user/0/com.xyz_app2/cache/react-native-image-crop-picker/7.jpg", "index": 1, "modalHt": 780.1354401805869, "modalWidth": 360, "sortFn": [Function move], "width": 352.8}
[Sat Aug 15 2020 17:42:19.467] LOG object
[Sat Aug 15 2020 17:42:19.484] LOG ani code
[Sat Aug 15 2020 17:42:20.868] LOG [TypeError: undefined is not an object (evaluating '_this.props.img_source')] //<<==here is the error
But there is an error saying that this.props.img_source is undefined when load an component:
<GridImage
img_source={img_source} //<<==this line causes error as img_source undefined
width={width}
ht={ht}
indx={index}
modalWidth={modalWidth}
modalHt={modalHt}
/>
It is a very straight forward object destructing. What is wrong here?

Related

State Variable not being correctly captured, when passing through components

I have excluded some parts of my original code for readability, sorry if it causes any confusion!
I have a state variable in App.js defined as such
const [tasks, setTasks] = useState([])
From App.js, I pass into Tasks.js the state variable as a
prop.
Tasks.js receives the prop and sorts it as below (when a certain button is clicked)
const Tasks = function ({tasks, setTasks}) {
setTasks(tasks.sort((a, b) => {
if ((moment(a.isoDay).unix()) < (moment(b.isoDay).unix())) return -1
else {
return 0
}
}))
}
This causes the state variable in App.js to be updated, and this state variable is
passed into Calendar.js (from App.js) as a prop as well, as seen below
const Calendar = ({tasks}) => {
function TaskToCalendar(tasks) {
console.log(tasks)
console.log(tasks[0])
}
}
However, I am not accurately capturing the value of tasks.
For example, console.log(tasks) yields this before it is
sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test0", day: "Tue Jun 01 2021"}
1: {text: "Test1", day: "Wed Jun 02 2021"}
and yields this after it is sorted in Tasks.js
(2) [{…}, {…}]
0: {text: "Test1", day: "Wed Jun 02 2021}
1: {text: "Test0", day: "Tue Jun 01 2021}
But, console.log(tasks[0]) yields this before and
after it is sorted
{text: "Test0", day: "Tue Jun 01 2021"}
I have to click on another button somewhere in my UI (that runs an unrelated function), for console.log(tasks[0]) to yield {text: "Test1", day: "Wed Jun 02 2021} after sorting.
How would I go about correctly passing the value of tasks, such that accessing the array indices gives me the correct values?
The SetTask function is working asynchronously. hence, this behavior.
For logging the value you can use the useeffect Hook

Pulling Out Ids From Separate Objects And Plugging Into Function

I am trying to plug individual id's into a function to pull log outputs for each id. These ids are inside objects inside a larger object. I cannot figure out how to call these id's individually in order to print out the log report for each object.
objects
(2) [{…}, {…}]
0: {id: "60844b1f5ce50a40c1adfc32", rdbmsJobId: null, sqoopJobId: "30471e65-c9b9-40e0-b27f-472769480f0c", status: "FINISHED", progress: 100, …}
1: {id: "60844b1f5ce50a40c1adfc33", rdbmsJobId: null, sqoopJobId: "1e74fb62-4a61-420b-9c78-e005007eb17e", status: "FINISHED", progress: 100, …}
length: 2
__proto__: Array(0)
Function
getLogDataById(id: string){
this.logService.getLogById(id).subscribe(logRes => {
this.logReport = logRes
console.log("Log report is: " + this.logReport)
})
}
Expected Output
{
"id": "60844b1f5ce50a40c1adfc34",
"jobId": "60844b1f5ce50a40c1adfc32",
"log": "2021-04-24 16:45:20,180 INFO sqoop.Sqoop: Running Sqoop version: 1.4.7\n2021-04-24 16:45:21,084 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.\nWarning: /opt/sqoop/../hbase does not exist! HBase imports will fail.\nPlease set $HBASE_HOME to the root of your HBase installation.\nWarning: /opt/sqoop/../hcatalog does not exist! HCatalog jobs will fail.\nPlease set $HCAT_HOME to the root of your HCatalog installation.\nWarning: /opt/sqoop/../accumulo does not exist! Accumulo imports will fail.\nPlease set $ACCUMULO_HOME to the root of your Accumulo installation.\nWarning: /opt/sqoop/../zookeeper does not exist! Accumulo imports will fail.\nPlease set $ZOOKEEPER_HOME to the root of your Zookeeper installation.\nJob Created and Saved to Sqoop.\nSqoop Job Submitted to Yarn\n2021-04-24 16:46:27,894 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\n2021-04-24 16:46:28,051 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032\nContainer: container_1618958577187_0219_01_000001 on ip-172-31-50-48.us-west-2.compute.internal_43829\nLogAggregationType: AGGREGATED\n=====================================================================================================\nLogType:stderr\nLogLastModifiedTime:Sat Apr 24 16:46:26 +0000 2021\nLogLength:1722\nLogContents:\nApr 24, 2021 4:46:02 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory register\nINFO: Registering org.apache.hadoop.mapreduce.v2.app.webapp.JAXBContextResolver as a provider class\nApr 24, 2021 4:46:02 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory register\nINFO: Registering org.apache.hadoop.yarn.webapp.GenericExceptionHandler as a provider class\nApr 24, 2021 4:46:02 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory register\nINFO: Registering org.apache.hadoop.mapreduce.v2.app.webapp.AMWebServices as a root resource class\nApr 24, 2021 4:46:03 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate\nINFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'\nApr 24, 2021 4:46:03 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory getComponentProvider\nINFO: Binding org.apache.hadoop.mapreduce.v2.app.webapp.JAXBContextResolver to GuiceManagedComponentProvider with the scope \"Singleton\"\nApr 24, 2021 4:46:04 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory getComponentProvider\nINFO: Binding org.apache.hadoop.yarn.webapp.GenericExceptionHandler to GuiceManagedComponentProvider with the scope \"Singleton\"\nApr 24, 2021 4:46:06 PM com.sun.jersey.guice.spi.container.GuiceComponentProviderFactory getComponentProvider\nINFO: Binding org.apache.hadoop.mapreduce.v2.app.webapp.AMWebServices to GuiceManagedComponentProvider with the scope \"PerRequest\"\nlog4j:WARN No appenders could be found for logger (org.apache.hadoop.mapreduce.v2.app.MRAppMaster).\nlog4j:WARN Please initialize the log4j system properly.\nlog4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n\nEnd of LogType:stderr\n***********************************************************************\n\n\nEnd of LogType:stdout\n***********************************************************************\n\nContainer: container_1618958577187_0219_01_000003 on ip-172-31-50-48.us-west-2.compute.internal_43829\nLogAggregationType: AGGREGATED\n=====================================================================================================\nLogType:stderr\nLogLastModifiedTime:Sat Apr 24 16:46:26 +0000 2021\nLogLength:227\nLogContents:\nLoading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.\n\nEnd of LogType:stderr\n***********************************************************************\n\n\nEnd of LogType:stdout\n***********************************************************************\n\nContainer: container_1618958577187_0219_01_000002 on ip-172-31-50-48.us-west-2.compute.internal_43829\nLogAggregationType: AGGREGATED\n=====================================================================================================\nLogType:stderr\nLogLastModifiedTime:Sat Apr 24 16:46:26 +0000 2021\nLogLength:227\nLogContents:\nLoading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.\n\nEnd of LogType:stderr\n***********************************************************************\n\n\nEnd of LogType:stdout\n***********************************************************************\n\nIngestion Finished"
}

Cookies.set doesn't set the value in cookie (js-cookie)

I'm trying to set the some data inside of cookie using js-cookie.
but somehow it's not setting in the cookie. following is my code:
const setCookie = (name: string, value: string, expires: Date) => {
Cookies.set(name, value, {expires})
}
and this is the result when I console.log this line :
UserId=1; path=/; expires=Thu, 09 Apr 2020 15:26:37 GMT
I thought that path=/ is the problem, so I've tried to set the path as well, but didn't work.
Does anyone have idea why is not setting into the cookie?
Updated:
data passed to name, value, expires are :
UserId, 1, Thu Apr 09 2020 11:26:37 GMT-0400 (Eastern Daylight Time)
Expires parameter should be a number which indicate how much days until your cookie will expire
just update your function as follow
const setCookie = (name: string, value: string, expires: number) => {
Cookies.set(name, value, {expires})
}

How to I custom my log format in winston-papertrail?

I am making an app based on typescript and trying to implement winston-papertrail for logs with a timestamp and custom format. The problem is that when I am consoling it, it is showing exacltly what I want but on papertrail it is showing in an unexpected way. Here is my code on the typescript.
const { Papertrail } = require("winston-papertrail");
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, prettyPrint, printf } = format;
const timezoned = () => {
return new Date().toLocaleString("en-US", {
timeZone: "Asia/Kolkata",
});
};
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const options = {
console: {
level: "debug",
format: combine(
timestamp({format: timezoned}),
myFormat,
) ,
},
};
const winstonPapertrail = new Papertrail({
host: "logs3.papertrailapp.com",
port: 32795,
level: "info",
});
const consoleWinston = new transports.Console(options.console);
export const logger = createLogger({
transports: [winstonPapertrail, consoleWinston],
});
How I am getting it on the console (which is the correct format) :
10/26/2019, 11:15:49 PM info: Fetching offset:16000 count:1000
10/26/2019, 11:15:59 PM info: Products Fetched
10/26/2019, 11:15:59 PM info: Indexing Products
How it is showing on papertrail:
Oct 26 23:15:50 wolborg default info { message: 'Fetching offset:16000 count:1000',
Oct 26 23:15:50 wolborg default info level: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(message)]:
Oct 26 23:15:50 wolborg default info '{"message":"Fetching offset:16000 count:1000","level":"info"}' }
Oct 26 23:15:59 wolborg default info Products Fetched
Oct 26 23:15:59 wolborg default info { message: 'Products Fetched',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Products Fetched","level":"info"}' }
Oct 26 23:15:59 wolborg default info Indexing Products
Oct 26 23:15:59 wolborg default info { message: 'Indexing Products',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Indexing Products","level":"info"}' }

Angularjs send empty JSON to server (ONLY in IE 9 and greater)

I have a little issue with my angularjs script.
I'm trying to post data to server (PHP script which saves values to database).
It works correctly in Chrome, Mozilla, Opera and each other but totally not in IE. I tried IE9, 10 and also 11 (all without add-ons)and still can't figure it out.
In IE my angularjs posts only empty JSON (something like {}).
Here's my angularjs POST script.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/newInvoice.php',
data : $scope.invoice, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
getInvoices();
$scope.invoice = {items: [{qty: 1,description: '',cost: 0,taxPerc: 21}],odberatel: '',konecny_prijemce: '',datum_objednavky: new Date(),datum_vystaveni: new Date(),datum_splatnosti: new Date(),datum_zdanitelneho_plneni: new Date(),zpusob_uhrady: 'Platba kartou',dodaci_metoda: 'Osobní odběr'};
});
};
And here's PHP.
<?php
require_once '../includes/db.php'; // The mysql database connection script
$created = date("Y-m-d H:i:s", strtotime("now"));
$query = "SELECT id FROM ang_faktury ORDER BY id DESC";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$last_invoice_id = intval($row["id"]);
$year = date("Y");
$month = date("m");
$idString = str_pad(($last_invoice_id + 1), 5, '0', STR_PAD_LEFT);//id faktury ang_faktury[id], ang_faktury_polozky[id_faktury]
$faCislo = 'OB/'.$year.'/'.$month.'/'.$idString; //cislo faktury ang_faktury[cislo_faktury]
$_POST = json_decode(file_get_contents('php://input'), true);
$dzp = $_POST['datum_zdanitelneho_plneni'];
$datum_zdanitelneho_plneni = substr($dzp, 0, 10);
$dzpForm = date("d.m.Y", strtotime($datum_zdanitelneho_plneni));
$do = $_POST['datum_objednavky'];
$datum_objednavky = substr($do, 0, 10);
$doForm = date("d.m.Y", strtotime($datum_objednavky));
$dv = $_POST['datum_vystaveni'];
$datum_vystaveni = substr($dv, 0, 10);
$dvForm = date("d.m.Y", strtotime($datum_vystaveni));
$ds = $_POST['datum_splatnosti'];
$datum_splatnosti = substr($ds, 0, 10);
$dsForm = date("d.m.Y", strtotime($datum_splatnosti));
foreach($_POST['items'] as $item){
$sumPriceTotal += $item['priceTotal'];
$query2="insert into ang_faktury_polozky (id_faktury,name,cena,ks,dph_proc,dph,total) values('$idString','$item[description]','$item[mjPrice]','$item[qty]','$item[taxPerc]','$item[taxSum]','$item[priceTotal]')";
$mysqli->query($query2);
}
$spt = "{$sumPriceTotal}";
$cbd = (($spt*100)/121);
$dph = $spt - $cbd;
$query3="insert into ang_faktury (id,created_at,cislo_faktury,datum_zdanitelneho_plneni,odberatel,konecny_prijemce,zpusob_uhrady,dodaci_metoda,cislo_objednavky,datum_objednavky,datum_vystaveni,datum_splatnosti,cena_bez_dph,dph,celkem_k_uhrade) values('$idString','$created','$faCislo','$dzpForm','$_POST[odberatel]','$_POST[konecny_prijemce]','$_POST[zpusob_uhrady]','$_POST[dodaci_metoda]','$faCislo','$doForm','$dvForm','$dsForm','$cbd','$dph','$spt')";
$mysqli->query($query3);
mysqli_close($mysqli);
?>
Thanks for any advise.
check your data before sending console.log(data),
and check your data after receiving print_r($_POST) (in myFile.php)
from console (newInvoice.php):
Array
(
[items] => Array
(
[0] => Array
(
[qty] => 1
[description] => MIKI_01
[cost] => 10
[taxPerc] => 21
[priceTotal] => 10.00
[taxSum] => 1.74
[mjPrice] => 8.26
)
[1] => Array
(
[qty] => 1
[description] => MIKI_02
[cost] => 20
[taxPerc] => 21
[priceTotal] => 20.00
[taxSum] => 3.47
[mjPrice] => 16.53
)
)
[odberatel] => MIKI
[konecny_prijemce] =>
[datum_objednavky] => 2016-01-16T13:39:32.554Z
[datum_vystaveni] => 2016-01-16T13:39:32.554Z
[datum_splatnosti] => 2016-01-16T13:39:32.554Z
[datum_zdanitelneho_plneni] => 2016-01-16T13:39:32.554Z
[zpusob_uhrady] => Platba kartou
[dodaci_metoda] => Osobní odběr
)
Console (app.js)
Object {items: Array[2], odberatel: "MIKI", konecny_prijemce: "", datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time), datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)…}
datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_splatnosti: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_zdanitelneho_plneni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
dodaci_metoda: "Osobní odběr"
items: Array[2]
0: Object
$$hashKey: "object:4"
cost: 10
description: "MIKI_01"
mjPrice: "8.26"
priceTotal: "10.00"
qty: 1
taxPerc: 21
taxSum: "1.74"
__proto__: Object
1: Object
$$hashKey: "object:69"
cost: 20
description: "MIKI_02"
mjPrice: "16.53"
priceTotal: "20.00"
qty: 1
taxPerc: 21
taxSum: "3.47"
__proto__: Object
length: 2
__proto__: Array[0]
konecny_prijemce: ""
odberatel: "MIKI"
zpusob_uhrady: "Platba kartou"
__proto__: Object

Categories