Load all data from local database - javascript

I am using react-native-gifted-chat(https://github.com/FaridSafi/react-native-gifted-chat) to create a chat interface on my app, I want to load messages from my database.
I am using realm, and I am able to load the data but my code below loads only the first row of the data. I want to be able to load all the data from the database.
let chatData = realmDatabase.objects(DatabaseTableNames.chatTable);
let data=[];
for (let message of chatData ){
data = [{
_id: message.chatUniqueID,
text: message.msgBody,
createdAt: (new Date()).getTime(),
user: {
_id: message.chatUniqueID,
name: message.senderName
}
} ]
}
console.log(data)
I want to be able to load all the data from the database not only the first row, like the sample below.
[
{
_id: Math.round(Math.random() * 1000000),
text:
"It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/",
createdAt: new Date(Date.UTC(2016, 7, 31, 17, 20, 0)),
user: {
_id: 1,
name: "Developer"
},
},
{
_id: Math.round(Math.random() * 1000000),
text: "React Native lets you build mobile apps using only JavaScript",
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
sent: true,
received: true,
user: {
_id: 2,
name: "Developer"
},
}
];

Doing data = [{...}] in the for loop, will assign the last value of message to data. To get all the values, you need to push the items in the data array. You can do it like this:
let chatData = realmDatabase.objects(DatabaseTableNames.chatTable);
let data=[];
for (let message of chatData ){
data.push({
_id: message.chatUniqueID,
text: message.msgBody,
createdAt: (new Date()).getTime(),
user: {
_id: message.chatUniqueID,
name: message.senderName
}
});
}
console.log(data)

Related

Extract data from Shopify into a Google Sheet using Google Apps Script

I am trying to get specific product fields of a JSON object to send to a google sheet. The log tells me that 'console.log(productTitle)' is undefined and that 'Error: TypeError: products.forEach' is not a function. The structure of the Shopify object is below.
function getProducts() {
//set up url
const url = 'https://*****.myshopify.com/admin/'
const endpoint = 'products.json'
//set up parameters
const params = {
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': '*****'
},
muteHttpExceptions: true
}
try {
//call the url to fetch access token
const response = UrlFetchApp.fetch(url + endpoint, params)
//parse the response and get the access token
const products = JSON.parse(response.getContentText())
console.log(response)
console.log(products)
products.forEach(product => {
const productTitle = product.products_title
console.log(productTitle)
const productId = product.products_id
const productStatus = product.products_status
})
return result
}
catch (e) {
console.log('Error: ' + e)
}
}
/* { products:
[ { id: 121345678910,
title: 'Title',
body_html: 'Body Text',
vendor: 'Vendor Name',
product_type: 'candyrack_generated',
created_at: '2021-07-18T11:04:34-05:00',
handle: 'extended-warranty-1',
updated_at: '2022-10-11T09:15:18-05:00',
published_at: '2021-07-18T11:04:34-05:00',
template_suffix: 'water-pump',
status: 'active',
published_scope: 'web',
tags: '',
admin_graphql_api_id: 'gid://shopify/Product/121345678910',
variants:
[ { product_id: 121345678910,
id: 9876543210,
title: 'Default Title',
price: '9.95',
sku: '',
position: 1,
inventory_policy: 'continue',
compare_at_price: null,
fulfillment_service: 'manual',
inventory_management: null,
option1: 'Default Title',
option2: null,
option3: null,
created_at: '2021-07-20T08:43:11-05:00',
updated_at: '2022-10-11T09:14:17-05:00',
taxable: true,
barcode: '',
grams: 0,
image_id: null,
weight: 0,
weight_unit: 'kg',
inventory_item_id: 24681012,
inventory_quantity: -708,
old_inventory_quantity: -708,
requires_shipping: false,
admin_graphql_api_id: 'gid://shopify/ProductVariant/987654' } ],
options:
[ { product_id: 121345678910,
id: 909000,
name: 'Title',
position: 1,
values: [Object] } ],
images:
[ { product_id: 121345678910,
id: 3693336,
position: 1,
created_at: '2022-04-03T08:43:29-05:00',
updated_at: '2022-04-03T08:43:32-05:00',
alt: null,
width: 1080,
height: 1080,
src: 'http://cdn.shopify.com/s/files/1/0541/4132/13/products/freereplacements.png?v=164899',
variant_ids: [],
admin_graphql_api_id: 'gid://shopify/ProductImage/369333' } ],
image:
{ product_id: 121345678910,
id: 3693336,
position: 1,
created_at: '2022-04-03T08:43:29-05:00',
updated_at: '2022-04-03T08:43:32-05:00',
alt: null,
width: 1080,
height: 1080,
src: 'http://cdn.shopify.com/s/files/1/0541/4132/13/products/freereplacements.png?v=1648993',
variant_ids: [],
admin_graphql_api_id: 'gid://shopify/ProductImage/3693336' } }
*/
I would like to pull different keys into different columns to populate rows for all products. I would also like to know how to access the Finance Reports to pull into Sheets as well. I do get a successful return of all product data 'const products = JSON.parse(response.getContentText())' , can't separate the data. Thank you.
The log tells me that 'console.log(productTitle)' is undefined
Google Apps Script code does not run in the browser. It runs in a sandboxed environment on Google's servers, so logging works a little differently than what you might be used to in the browser. See the docs on Logging for Apps Script.
'Error: TypeError: products.forEach' is not a function
Take a second look at the Shopify response. It's structured as:
{
products: [...]
}
So your code products = JSON.parse(...) is actually referencing the response object, not the products array inside it. Try something like this:
const responseObj = JSON.parse(response.getContentText())
const products = responseObj.products
I would like to pull different keys into different columns to populate rows for all products. I would also like to know how to access the Finance Reports to pull into Sheets as well. I do get a successful return of all product data 'const products = JSON.parse(response.getContentText())' , can't separate the data.
You are on the right track with using forEach to loop through the products in the products array (once you fix the above issue) to get individual properties of each object.
To write the data out to a Google Sheet, you'll need to explore the setValues() API.
In short, you will need to structure the data from the Shopify response into a two-dimensional array to write the data to a sheet. Search Google for two-dimensional array javascript if you are not familiar with this concept; two-dimensional arrays are just a way of structuring tabular data, like that in a spreadsheet. Once you have your two-dimensional array, you will write it back to the Google Sheet with setValues().

Dynamically split an array into subarrays

const giftcards = [
{
fromuserid: 1,
amount: 10,
date: new Date(),
touserid: 11,
},
{
fromuserid: 1,
amount: 20,
date: new Date(),
touserid: 11,
},
{
fromuserid: 2,
amount: 10,
date: new Date(),
touserid: 11,
},
{
fromuserid: 2,
amount: 10,
date: new Date(),
touserid: 11,
},
{
fromuserid: 3,
amount: 10,
date: new Date(),
touserid: 11,
}
]
I achieved this, which is shown in the useEffect hook:
const giftcards = [
{
fromuserid: 1,
amounts: [{
amount: 10,
date: new Date(),
touserid: 11,
},
{
amount: 20,
date: new Date(),
touserid: 11,
}
]
},
{
fromuserid: 2,
amounts: [{
amount: 10,
date: new Date(),
touserid: 11,
},
{
amount: 10,
date: new Date(),
touserid: 11,
}
]
},
{
fromuserid: 3,
amounts: [{
amount: 10,
date: new Date(),
touserid: 11,
}]
}
]
The solution that was given works except that i would like to make it dynamic.
Meaning, in my app, I allow the user to arrange how the array will be sorted.
For example,
const [sort, setSort] = useState('fromuserid')
const [results, setResults] = useState([])
<div>
<select value={sort} onChange={(e)=> setSort(e.target.value)}>
<option value='fromuserid'>Sort by Buyer</option>
<option value='touserid'>Sort by Receiver</option>
<option value='date'>Sort by Date</option>
</select>
</div>
then in the:
useEffect(() => {
allgiftcards.forEach(({
fromuserid,
date,
from,
giftcardid,
message,
template,
touserid,
amount,
paid
}) => {
map.has(fromuserid) || map.set(fromuserid, {
fromuserid,
cards: []
})
map.get(fromuserid).cards.push({
date,
from,
giftcardid,
message,
template,
touserid,
amount,
paid
})
})
setResults([...map.values()])
}, [sort])
Here is what i mean by dynamic. If the user selected date, I would like for it to look something like:
useEffect(() => {
allgiftcards.forEach(({
fromuserid,
date,
from,
giftcardid,
message,
template,
touserid,
amount,
paid
}) => {
map.has(date) || map.set(date, {
date,
cards: []
})
map.get(date).cards.push({
date,
from,
giftcardid,
message,
template,
touserid,
amount,
paid
})
})
setResults([...map.values()])
}, [sort])
But It seems to me that having a bunch of if and else statements would be bad coding and would create a lot of extra code, so looking for a nice and clean solution
This really isn't a question of React (or where-ever useEffect comes from). This is really a general Javascript question, and it's a problem that suits itself well for solving with functional programming, or at least, with one of the staples of functional programming: reduce
In this case, you could supply the 2nd argument which is the initial value of the accumulator -- in this example an empty object works well. You can choose any key from the data to bucket the results:
// Choose a key that each object in the set has, e.g. 'fromuserid' or 'touserid'
const group_by = 'fromuserid';
let bucketed = giftcards.reduce(function (acc, x) {
let pivot = x[group_by]
let current_vals = (acc.hasOwnProperty(pivot) ? acc[pivot] : []);
current_vals.push(x);
acc[pivot] = current_vals;
return acc
}, {});
console.log(bucketed);
If you really needed to land on the second data structure you shared, you could jostle your initialValue and the exact placement of values into the accumulator, but hopefully this demonstrate the concept of how to dynamically choose how to group the data.
This codepen shows how to dynamically bucket an array of objects based on a specific property. Below is a sample of the callback function you can pass to the reducer -- included in the example.
function groupBy(accum, current, groupKey){
const val = current[groupKey]
const {[groupKey]:_, ...content} = current
if (val in accum){
accum[val].push(content)
}
else accum[val] = [content]
return accum
}

How to change the value of a field in an array mongodb nodejs

There are many array levels, that's why I can't choose the right field, I guess.
This is the Schema of the model:
{
season: 1,
finished: 0,
Games: [{
Game: [{
game: 1,
Players: [{
Id: 0,
name: "Peter",
jails: 3, //I want to change this value
pays: 1000,
gets: 2000,
points: 3
}]
}]
}]
}
I tried this query but it's not working:
Seasons.update({
season: 1,
game: 2,
Id: 0
}, {
jails: 4
},
(err, data) => {
if (err) {
console.log(err)
} else {
console.log(data)
}
}
)
I have used the $set propery but it didn't work as I want. It make changes all jails field of all players to same value in the same season. I mean, the query is selecting the most parent record, so it is the season record. But I want to change value of child element.

How to push array to nested child object of only matching parent properties?

Below is my JSON structure:
$scope.dataList = [{
CompanyName: null,
Location: null,
Client: {
ClientId: 0,
ClientName: null,
Projects:{
Id: 0,
Name: null,
}
}
}];
I have this data in dataList scope variable :
[{
CompanyName: XXXX,
Location: California,
Client:{
ClientId: 1,
ClientName: John Cena,
Projects:{
Id: 1,
Name: Abc,
}
}
}]
Now in the above record I need to find by company name and location and add Client array to matched company.
Now based on button click event I am getting 1 or more another record from http call like below:
[{
CompanyName: XXXX,
Location: California,
Client:[{
ClientId: 2,
ClientName: Undertaker,
Projects:{
Id: 2,
Name: Pqr,
}
}]
}]
Now I want to append this new client data to my dataList object for company XXXX and for location California.
This is how I am trying but I am getting errors:
$http.get("Url")
.then(function(data) {
for (var i = 0; i < data.length; i++) // when there will be more than 1 records in response i get from http call
{
var result = $.grep($scope.dataList, function (e)
{
//find records from dataList by Company name and Location
return (e.CompanyName == data[i].CompanyName) && (e.Location == data[i].Location);
});
//Push client Id 2 record in dataList
result.Client.push(data[i]);// error:result.Client is undefined
console.log(result);
}
});
You could use a check and move the content of Client into an array, before pushing to result.Client
if (!Array.isArray(result.Client)) { // check if not an array
result.Client = [result.Client]; // create one with the actual content
}
result.Client.push(data[i]);

Access data from an array with jquery

Im trying to loop through an array only i cant seem to extract the data from my array...
http://jsfiddle.net/338Ud/
var listTicker = function (options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function (index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function () {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array({
id: 0,
name: 'Antonia Lallement',
title: '\u003cp\u003e\u003cspan\u003eConsultant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started as a resourcer at company three months ago so I\u0026rsquo;m a new team member. Sin...',
image: 'antonia.jpg'
}, {
id: 1,
name: 'Camilla Gobel',
title: '\u003cp\u003e\u003cspan\u003eBusiness Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI joined company in 2011. As a multilingual Consultant, my initial focus was the provisi...',
image: 'camilla.jpg'
}, {
id: 2,
name: 'Mark Dorey',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Process, Subsea, Project, Safety)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eWhen I joined company I started as a resourcing specialist and worked across Search and ...',
image: 'mark.jpg'
}, {
id: 3,
name: 'Sadia Butt',
title: '\u003cp\u003e\u003cspan\u003eDiscipline Manager (Mechanical, Piping, Structural)\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI couldn\u0026rsquo;t have asked for a better company to work for! After working as a resourc...',
image: 'sadia.jpg'
}, {
id: 4,
name: 'Samantha Linnert',
title: '\u003cp\u003e\u003cspan\u003ePayroll Assistant\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI began at company as an operations assistant learning to spec CVs and post jobs. Shortl...',
image: 'samantha.jpg'
}, {
id: 5,
name: 'Simon Cottenham',
title: '\u003cp\u003e\u003cspan\u003eConsultant, Middle East\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI have been with company for exactly one year now, I never would have believed that I wo...',
image: 'simon.jpg'
}, {
id: 6,
name: 'Vicky Spencer',
title: '\u003cp\u003e\u003cspan\u003ePayroll Manager\u003c/span\u003e\u003c/p\u003e',
bio: '\u003cp\u003eI started my career at company in July 2012 initially covering maternity leave, managing...',
image: 'vicky.jpg'
});
$(function () {
listTicker({
list: textlist,
startIndex: 0,
trickerPanel: $('.textbox'),
interval: 3 * 1000,
});
});
you are adding object to a html .... use . operator to get the actual values
....
options.trickerPanel.fadeOut(function () {
$(this).html(value.id).fadeIn();
//--------^^^----here
}
i am taking id from the object and showing it in the div.. you can add whatever you need there..
$(this).html(value.title).fadeIn(); //to get title
fiddle here
$.each(textlist, function(index, value){
//do stuff with your array
});
Pasting just the diff, i tried to get the data here below.
From the code above.
options.trickerPanel.fadeOut(function () {
$(this).html(value).fadeIn();
});
The diff,
options.trickerPanel.fadeOut(function () {
$(this).html(value.bio).fadeIn();
});
The difference, is value is the entire array object being passed to the fadeOut function, accessing each elements in the array gives the result.

Categories

Resources