I have such a data structure:
data: [
{
current: true,
id: "3d6266501370d",
name: "Option",
items: [
{
hidden: false,
id: "ed716c12bf8f3",
data: "ffff",
}
],
selected_queries:[
{
id: 67896,
data: "ff",
}
]
},
]
and I need to edit just hidden filed of every object, other values I need to keep as it is. I created such a code:
export const editField = (id, status) => {
return new Promise((res) => {
const data = getData();
const newData = data.map(dataItem => {
if (dataItem.current) {
const newDataItem = dataItem.items.map(item => {
if (item.id === id) {
return Object.assign({}, item, {
...item,
hidden: status,
});
} else {
return item;
}
})
return newDataItem;
} else {
return dataItem;
}
})
res(newData);
});
}
but I get new object whch has null. Can somebody help me with this?
When you are calling data = getData() (per Marks's comment) it is assigning data = null until getData() returns. Only then is it getting updated. So newData = data.map... is being run on nothing. You could assign a callback on getData:
function getData(cb){
data = get the data..
cb(data)
}
//Then use it like:
const data = getData(function(data){
newData = data.map...
});
You could transform getData() in a Promise too, something like:
var promiseData = new Promise(function(resolve, reject) {
resolve(getData());
});
promiseData.then(function(data) {
// THE REST OF YOUR CODE USING "data"
}).catch(function(error){
console.error(error);
});
Then you'll be sure that you got the data you needed.
Related
Im trying to create a chrome extension, and have encountered an annoying problem. I have this function, where I add an object to my indexedDB if the urlKeyValue of that object, does not already exist in the database.
If the urlKeyValue does exist in the DB, i want to get the object in the DB that contains that value. This is where my problem begins. On line 184 - 188, i try to get the object by searching by the `urlKeyValue, but when I try to print the object, i get undefined.
Question: How to get an object from IndexedDB by a value?
This is how my objects are structured:
{
message: "insert",
payload: [
{
urlKeyValue: "",
url: {
[userId]: {
[time]: {
msg: form_data.get("message"),
},
},
},
},
],
}
My Function where it all happens:
function insert_records(records, when) {
if (db) {
const insert_transaction = db.transaction(["roster2"], "readwrite");
const objectStore = insert_transaction.objectStore("roster2");
return new Promise((resolve, reject) => {
insert_transaction.oncomplete = function () {
console.log("ALL INSERT TRANSACTIONS COMPLETE.");
resolve(true);
};
insert_transaction.onerror = function () {
console.log("PROBLEM INSERTING RECORDS.");
resolve(false);
};
records.forEach((person) => {
// the "when" varieable isnt important, just disregard it
if (when != "init") {
const index = objectStore.index("urlKeyValue");
let search = index.get(person.urlKeyValue);
search.onsuccess = function (event) {
if (search.result === undefined) {
// no record with that key
let request = objectStore.add(person);
request.onsuccess = function () {
console.log("Added: ", person);
};
}
else {
const request2 = objectStore.get(person.urlKeyValue);
request2.onsuccess = function (event) {
console.log("--------" + event.target.result);
};
}
};
} else {
// this else statement isnt really important for this question
let request = objectStore.add(person);
request.onsuccess = function () {
console.log("Added: ", person);
//self.location.href;
};
}
});
});
}
}
EDIT:
This is an example of an object I store:
let roster = [
{
urlKeyValue: "https://www.youtube.com/",
"https://www.youtube.com/": {
1: {
20: {
msg: "this is some init data",
},
},
},
},
];
I'm new to Node JS and still figuring out how API GET requests are working. I'm trying to call API GET request using Node Js, function is supposed to get data from the servers and url will be "url/books?name=" where "name" will be passed to the function from input field. So far I have this function
async function getBooksInfo(name) {
const url = `https://test/books?name=${name}`;
return new Promise(function (resolve, reject) {
https.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
resolve(body)
});
res.on("error", (e) => {
reject(e);
});
});
})
}
and another function will create stream of inputs,
async function storeInfo() {
const date = readLine().trim();
const result = await getBooksInfo(date);
const isEmpty = !Object.keys(result).length;
if (isEmpty) {
ws.write('We don't have this book in our database');
} else {
ws.write(`Book Name: ${result.bookName}`);
ws.write(`Year: ${result.year}\n`)
}
}
but for some reason stream of inputs return undefined, I don't seems to understand what could be the issue. Any help and suggestion is greatly appreciated.
Updated: this is what console.log shows
{
page: 1,
per_page: 100,
total_pages: 20,
data: [
{
bookName: 'test',
year: 1975,
author: "test,
}
]
}
I am trying to fetch data through Axios' request and push into an array. Here is my code:
props: [
'products',
],
data: function () {
return {
algolia: '',
products_data : [],
};
},
mounted() {
this.products_data = this.products;
}
methods: {
find () {
let new_product = {};
axios.get('/product/find?barcode=' + this.barcode)
.then(function (res) {
new_product.name = resp.data.name
new_product.barcode = resp.data.barcode
new_product.unit = resp.data.unit
this.products_data.push(new_product);
})
.catch(function (err) {
console.log(err);
})
},
}
I am getting the error Cannot read property 'products_data' of undefined sue to this line this.products_data.push(new_product); I am new in Vue. Any help would be highly appreciable.
Regards
this should work, i have removed function syntax and used arrow function.
find () {
let new_product = {};
axios.get('/product/find?barcode=' + this.barcode)
.then((resp) => {
new_product.name = resp.data.name
new_product.barcode = resp.data.barcode
new_product.unit = resp.data.unit
this.products_data.push(new_product);
})
.catch((err)=> {
console.log(err);
})
}
I'm trying to build the following use case of DataLoader together with Mongoose:
export const PurchaseOrderType = new GraphQLObjectType({
name: "PurchaseOrder",
description: "PurchaseOrder",
interfaces: () => [NodeInterface],
isTypeOf: value => value instanceof PurchaseOrderModel,
fields: () => ({
id: {
type: new GraphQLNonNull(GraphQLID),
resolve: obj => dbIdToNodeId(obj._id, "PurchaseOrder")
},
name: {
type: new GraphQLNonNull(GraphQLString)
},
customer: {
type: CustomerType,
resolve: (source, args, context) => {
return context.customerLoader.load(source.customer_id);
}
}
})
});
export default () => {
return graphqlHTTP((req, res, graphQLParams) => {
return {
schema: schema,
graphiql: true,
pretty: true,
context: {
customerLoader: customerGetByIdsLoader()
},
formatError: error => ({
message: error.message,
locations: error.locations,
stack: error.stack,
path: error.path
})
};
});
};
export const customerGetByIdsLoader = () =>
new DataLoader(ids => {
return customerGetByIds(ids);
});
export const customerGetByIds = async ids => {
let result = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();
let rows = ids.map(id => {
let found = result.find(item => {
return item.id.equals(id);
});
return found ? found : null; << === found always undefined
});
return rows;
};
I'm facing the following problems when loading several PurchaseOrders:
A single customer_id is being called more than once in the ids parameter of the DataLoader. So an example id 5cee853eae92f6021f297f45 is being called on several requests to my loader, in successive calls. That suggests that the cache is not working properly.
My found variable when processing the read result is always being set to false, even comparing the right ids.
You can use findOne
export const customerGetByIds = async ids => {
let result = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();
const rows = []
let promiseAll = ids.map(async (id) => {
let found = result.filter(item => item.id.toString() === id.toSring());
if(found) {
rows.push(found[0])
return found[0]
}
return null;
});
await Promise.all(promiseAll);
return rows;
};
I have array of customers and addresses endpoint URL as below
customerArray = [
{name:customer1, id: 1, address: {streetName: '123 lane'}},
{name:customer2, id: 2, address: {streetName: 'xyz lane'}},
{name:customer3, id: 3, address: {streetName: 'abc lane'}}
]
URL = 'id/addresses'
GET request for URL will return array of addresses based on customer ID
if we get empty array as response then we need to add address from "customerArray" for that id
// This is what I am doing to meet the requirement - seems this is not the right approach. Please help me to fix this
customerArray.forEach((customer) => {
const getObj = {
url: `${customer.id}/addresses`,
method: GET
};
axios(getObj)
.then((getResult) => {
if (getResult.length === 0) {
const postObj = {
url: `${customer.id}/addresses`,
method: POST,
data: customer.address
};
axios(postObj)
.then((postResult) => {
// I am not sure what to do here - I leaving blank so iteration will continue
})
.catch((err) => {
res.status(400).json(err);
});
}
})
.catch((err) => {
res.status(400).json(err);
});
});
Please help me to fix it
I think you don't know how to get the final data. Basically, you should put your promises into an array and you Promise.all to wait for all of them to finish.
Please comment if something wrong. Hope this helps
const promises = customerArray.map((customer) => {
const getObj = {
url: `${customer.id}/addresses`,
method: GET
};
return axios(getObj)
.then((getResult) => {
if (getResult.length === 0) {
return {
url: `${customer.id}/addresses`,
method: POST,
data: customer.address
};
}
return null;
})
.then((postObj) => {
if (postObj) {
return axios(postObj)
}
return null
})
});
Promise.all(promises)
.then(result => {
// the result is a list of data from axios(postObj)
console.log(result);
res.json(result);
})
.catch((err) => {
res.status(400).json(err);
});