Why doesn't the first click of my checkbox do anything? - mongodb

I have a nested array of todo objects and I'm trying to change the boolean value of completed. Whenever I send a request with postman the database always changes. However the first time I click on my checkbox I still get a response but the database doesn't get updated. Only after the first click do subsequent clicks actually update my database. I should note that if the initial value of completed is true, the checkbox works right away.
`module.exports.update = (req, res) => {
Users.updateOne(
{"todos._id" : req.body.id},
{ "$set": { "todos.$.completed" : req.body.completed } }
)
.then(res => res.json({res: res}))}`
In my response I'm also noticing that I get a value modificationCount which starts at 0 on my first click and then has the value of 1 every subsequent click.
Here's my request function in case its important.
`function handleCheck(e) {
setCompleted(!completed)
axios.put('http://localhost:8000/api/users/update/not',
{
id: e,
completed: completed
})
.then(res => {
console.log(res.data.user)
setLoad(load - 1)})}`

Related

Axios/mongodb request, PromiseState stuck on pending, then() part is not called

I'm trying to update my mongodb database in javascript by accessing some documents from the database, changing a specific document and then performing a patch request via axios.
When I get to the patch request I'm able to update the database however the promise is stuck on pending and thus, the then() part of the code is not run.
This is the main structure of the code:
In the first part the documents are requested from the database via axios.get:
function updateDocument(someinputdata){
g = axios.all([axios.get('/getData1),axios.get('/getData2)])
.then(response => {
Data1 = response[0].data;
Data2 = response[1].data;
adjustData(Data1,Data2);
});
}
In the second part a specific document is changed and a patch request is called:
function adjustData(Data1,Data2){
...getting specific document and change value from specific field...
var newRec = {
title: "dummyTitle",
rate: newRateValue
};
promise = axios({
url: '/patch/The Real Title',
method: 'PATCH',
data: newRec,
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('I want this text to display but it doesn't')
});
}
If I console.log(promise):
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
On the server side I have this:
router.patch('/patch/:title', (req,res) => {
const updatedPost = Model.updateOne(
{ "title": req.params.title},
{ $set: { "rate" : req.body.rate}},
(err, result) => {
if(err) {
console.log(err);
throw err;
}
})
.then(
console.log('This text is displayed');
)
})
I want to use the first then() part to update some HTML
Why is the patch request stuck on pending (so not fulfilled or rejected)?
I've figured out what my problem was.
I needed to add
res.json({msg: "Your data has been saved"});
to the code on the server side.

How can I test the content in ag-grid using testing-library?

I am trying to write a few simple tests that the headers and data I want to render are showing up as expected. I created a repo - https://github.com/olore/ag-grid-testing-library to reproduce. The table looks as I would expect when opened in a browser.
<AgGridReact
columnDefs={ /* First 2 always findable, others never */
[
{ field: "make" },
{ field: "model" },
{ field: "price" },
{ field: "color" },
]}
rowData={
[{
make: "Toyota",
model: "Celica",
price: "35000",
color: "blue"
}]
}
pagination={true}></AgGridReact>
And the tests
test('renders all the headers', async () => {
const { getByText } = render(<GridExample />);
expect(getByText("Make")).toBeInTheDocument(); // PASS
expect(getByText("Model")).toBeInTheDocument(); // PASS
expect(getByText("Price")).toBeInTheDocument(); // FAIL
expect(getByText("Color")).toBeInTheDocument(); // FAIL
});
Locally, the first 2 column headers and data are accessible, but none of the other columns are rendered, as I can see in the output of testing-library. I am using --env=jsdom-fourteen as recommended by other posts.
Strangely enough, no headers or data are rendered for the tests when in the codesandbox for this repo, as with local, the browser looks correct.
https://codesandbox.io/s/gallant-framework-e54c7. I then tried waiting for gridReady
https://codesandbox.io/s/intelligent-minsky-wl17y, but it didn't make a difference.
EDIT: Also tried directly calling a function in onGridReady, same problem (first 2 columns pass, second 2 fail)
test('renders all the headers', async (done) => {
let page;
const onReady = () => {
expect(page.getByText("Make")).toBeInTheDocument(); // PASS
expect(page.getByText("Model")).toBeInTheDocument(); // PASS
expect(page.getByText("Price")).toBeInTheDocument(); // FAIL
expect(page.getByText("Color")).toBeInTheDocument(); // FAIL
done();
}
page = render(<GridExample ready={onReady}/>);
});
ag-grid uses Column Virtualisation, so it seems the solution here is to disable it via the suppressColumnVirtualisation attribute on the <AgGridReact> element.
<AgGridReact
suppressColumnVirtualisation={true}
...
Boom! All the tests pass!
In reality, it's probably ideal to only suppress this during testing:
suppressColumnVirtualisation={process.env.NODE_ENV === "test"}
An addition to #olore's answer.
If you use server side data source, make sure
Your mock server responds with expected data, not error.
You use asynchronous selector in testing library, at least for the first cell of the row.
expect(await findByText('Price')).toBeInTheDocument();

Sequelize js transaction on destory and bulkCreate not rolling back

I am trying to delete all report_details before bulkCreate/insert the new ones. The problem is when there is an error in bulkCreate it does not rollback. It should bring the destroyed report_details back but it is not working.
The way i am testing this transaction code is I insert the report_details and then manually change one column name so that when inserting again it gives column error. and transaction should rollback but in actual report_details are destroyed and on bulkCreate error it does not bring back destroyed report_details
can some one please take a look on my code. I have search on google my syntax is correct.
and how do i test transactions on my machine ? instead of changing the column name is there any other way to produce error?
function saveReportsDetails(results) {
db.report_detail.bulkCreate(results.report.objAllReportsDetail);
return db.snpreq.transaction(t => {
// transaction block
return db.report_detail.destroy({
where: {
profile_id: results.profile.data[0].id
}
}, {
transaction: t
}).then(deleted => {
console.log('*******TRANSACTION DELETED*********');
return db.twenreport_detail.bulkCreate(results.report.objAllReportsDetail, {
transaction: t
}).then(reports_created => {
console.log('*******TRANSACTION bulk created*********');
});
});
}).then(transaction => {
console.log('********All Transaction********');
}).catch(err => {
console.log('*******ROLL BACK*********');
});
}
There was error in m code syntax. In delete transaction it takes transaction: t in single argument
like this
return db.twentythree_and_me_report_detail.destroy({
where: {
profile_id: results.profile.data[0].id
},
transaction: t
})
I was not receiving any kind of syntax error or any other error. so, i just kept search and found answer

vue js 2 - for loop in multiple rest calls fetchData

I am trying to get wp-rest and Vuejs 2 to work together, so far things are coming along nicely apart from this one rest call that requires another request for the design to be complete. Essentially I want to be able to iterate / loop through the first request and dynamically change update the second request.
And my second question is performance, overall the rest calls are taking a bit longer to load - is there something I can do to optimize?
Context:
The first result data gives me an id, slug and title to all the posts I want to display only on the homepage as featured - through that id or slug I want to pass it to the second request - so I can pull in more information about those posts - like featured image and other meta field data.
<pre>export default {
name: 'work',
data () {
return {
loading: false,
page: null,
pagesingle: null,
error: null
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
this.$http.get('/cms/wp-json/wp/v2/pages/?slug=work&_embed')
.then(result => {
this.page = result.data
this.$http.get('/cms/wp-json/wp/v2/cases-studes/?slug=case-study-name').then(
result => this.pagesingle = result.data
);
})
}
}
}</pre>
I think you want to look at Promise.all. It will take an array of promises, wait for them all to complete, and then resolve with an array of results.
You would build your array of promises based on the array of slugs and ids in your first request. Maybe something like
const promises = result.data.articles.map((article) =>
this.$http.get(`/cms/wp-json/wp/v2/cases-studies/?slug=${encodeURIComponent(article.slug)}`)
);
Getting the results is as easy as
Promise.all(promises).then((results) => {
this.arrayOfSinglePages = results.map((result) => result.data);
});
Now your this.page has the array of id (and stuff) and this.arrayOfSinglePages has the page details for each of them in the same order.

Mongoldb, issue with deleting and saving data to a collection

I am having some issue with removing objects in my database. I have a collection called menus which consists of several object where each object is an item in the menu. Here is how it looks :
{
"_id":ObjectId("583b7577e1206be8ee79f062"),
"restID":"583972080daa6ece0960778c",
"itemName":"buffallo chicken wings",
"subType":"Appetizers/Starters",
"cuisine":"American",
"description":"descritption of buffallo chicken wings",
"duration":"All",
"quantity":"6",
"cost":"10.95",
"__v":0
}
Now I have a X button next to each item in my frontend. The code below shows how I am trying to delete an item (when user clicks the X button) on my server side. After debugging this I observed that it is splicing the object that I want to delete but it is not updating the database. I don't understand why. Am I doing something wrong?
module.exports.removemenu = function(req, res) {
var menuId = req.body.itemId;
Menu.find({}, function(err, results){
results.map(function(menu, index){
if(menu._id == menuId) {
results.splice(index, 1);
}
menu.save();
})
res.json({res: 'success', data: results});
})
}
Are you upserting the changes to the database afterwards?
Use remove command to delete record from collection
db.restaurants.remove( { "borough": "Manhattan" } )