I am declaring dateRangePicker field in component state like below
dateRangePicker: {
selection: {
startDate: new Date(),
endDate: new Date(),
key: 'selection',
},
}
later start date and end date changes as below
let startDate = "2019-04-16";
let endDate = "2019-05-16";
But, I am not able to update these value in state after following code block
this.setState({
dateRangePicker.selection.startDate : startDate,
dateRangePicker.selection.endDate : endDate,
})
I want to update the start and end date accordingly
It doesn't work the way you showed. It should be like this:
this.setState(ps=>({
...ps,
dateRangePicker:{
...ps.dateRangePicker, // Copy old data
selection: {
...ps.dateRangePicker.selection, // Same here
startDate: startDate
endDate: endDate
},
}
}))
We use functional form of setState, because you can see at one point we access data from previous state: ps.selection
what your'e tryin to acheive is to change the state of a deep/nested
object in setState..
const startDT = "new start date"
const endDT = "new end date"
this.setState(prevState => ({
...prevState,
dateRangePicker: {
...prevState.dateRangePicker,
selection: {
...prevState.dateRangePicker.selection,
startDate: prevState.startDate = startDT,
endDate: prevState.endDate = endDT,
}
}})
)
Or,
// copy without reference..
const dateRangePicker = { ...this.state.dateRangePicker }
dateRangePicker.selection = {
startDate: startDT,
endDate: endDT,
}
this.setState({ dateRangePicker })
The state is a immutable object, so you can not modified it, but create a new one, so using spread ... expression to create a new state.
Related
I originally had this mongoose schema:
const scriptsSchema = mongoose.Schema({
title: {
type: String,
require: true
},
updated: {
type: Date,
default: Date.now(),
require: true
}
});
export default mongoose.models.Script || mongoose.model('Script', scriptsSchema)
That i updated to
const constructDate = () => {
var today = new Date();
return (today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate())
}
const scriptsSchema = mongoose.Schema({
title: {
type: String,
require: true
},
updated: {
type: Date,
default: constructDate(),
require: true
}
});
export default mongoose.models.Script || mongoose.model('Script', scriptsSchema)
Since I wanted to have only the date (no time) as a default value in the 'updated' field. Problem is, the change does not reflect and whenever I create a new script document, the default 'updated' value is still Date.now().
I tried dropping the collection, resetting the database... but somehow it doesen't notice the changes I've made in the schema.
My problem is not about updating the existing documents, since I am still in developement phase and I don't mind dropping all documents in the database. I just want the schema to update to its new version.
for example I have documents with this field:
startDate: 2021-04-14T22:00:00.000+00:00
endDate: 2021-04-19T22:00:00.000+00:00
and I want to get all documents where a specific date (like today) is in the date range.
Is it possible to make such a query?
For example if I search for 18th April, then I get that document.
I thought something like this:
db.posts.find(
{
$gte: { startDate: new Date() },
$lt: { endDate: new Date() }
});
But this doesn't work... I get an error The provided parameters were invalid. Check your query and try again.
I think new Date() is not correct in Node.js?
EDIT:
This is my Controller:
const getActiveTours = async (req, res) => {
try {
const activeTours = await Tour.find({
startDate: { $gte: new Date() },
endDate: { $lt: new Date() },
}).exec();
res.status(200).send(activeTours);
} catch (error) {
return res.status(500).send({ errorMessage: error });
}
};
I exported it and here is my endpoint:
router.get('/getactivetours', tourController.getActiveTours);
I tried to call this in Postman but get an empty [] back...
Your syntax is wrong, try this one:
db.posts.find(
{
startDate: {$gte : new Date() },
endDate: {$lt : new Date() }
});
I'm a bit new to Vue and was wondering how to get the the past month date: I have this code:
import SomeTable from "./table/SomeTable";
export default {
name: "Cabinets",
components: {SomeTable},
data() {
return {
defaultColumns: [
'id',
'serialNumber'
],
defaultStartDate: new Date(),
defaultEndDate: new Date('2019-10-07')
}
},
props: {
startDate: {type: Date, required: false},
endDate: {type: Date, required: false},
}
}
</script>
And then I put defaultStartDate and defaultEndDate in the SomeTable element as follows:
<some-table :start-date="defaultStartDate" :end-date="defaultEndDate" :default-columns="defaultColumns"></some-table>
Which then returns the correct startDate of today and also the set one. But when i try for instance to do something like this:
defaultEndDate: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate()
My local environment turns blank and get all sorts of errors. I think this is due to the fact I can't use Javascript in that place in Vue? But again I'm really not yet sure how Vue works and couldn't find much on it by googling. So how could I do this using Javascript or maybe even if Vue has a neat trick for it?
EDIT:
the errors i'm getting are of the form:
Error in data(): "TypeError: Date().getFullYear is not a function"
But then with all the javascript functions i used inside Vue. And also
Invalid prop: type check failed for prop "endDate". Expected Date, got String with value "2019-9-5".
In your codes, endDate: {type: Date, required: false}, means endDate should be in Date type.
So you need to convert calculated value into Date like below:
defaultEndDate: new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()}-${(new Date()).getDate()}`)
EDIT:
And you need to think of the month is January(0). By using the above method, you will get error when it is on January.
I think It could be better to use computed value like below;
computed: {
defaultEndDate() {
const now = new Date();
now.setMonth(now.getMonth() - 1);
return new Date(now.toJSON().slice(0, 10));
}
}
I am using firebase cloud function to trigger a database update when a field is created on my database.
exports.dbTest2 = functions.database.ref('/{uid}/ignore')
.onCreate((snapshot, context) => {
const uid = context.params.uid
console.log(`Current User ${uid}`)
// Data added at the location
const ignoreData = snapshot.val()
const endTime = new Date(ignoreData.endTime).toString()
// ref matches `/{uid}/ignore`
return snapshot.ref.parent.child('schedule').set({
allDay: false,
endDate: new Date().toString(),
id: 100,
startDate: new Date().toString(),
title: 'test'
})
});
This function gets triggered when I add ignore to my real-time database. When this gets triggered, it looks like below:
However, I want ignore to be an array-like structure that has indices where each index contains the object. Something like this:
I also tried something like return snapshot.ref.parent.child('schedule').child().set(...
but didn't work because child() requires a parameter.
Any help?
You can simply pass an array with objects:
return snapshot.ref.parent.child('schedule').set(
[
{
allDay: false,
endDate: new Date().toString(),
id: 100,
startDate: new Date().toString(),
title: 'test1'
},
{
allDay: false,
endDate: new Date().toString(),
id: 101,
startDate: new Date().toString(),
title: 'test2'
}
]
);
How it looks in my firebase(photos are passed as array):
I'm getting frequent errors when i start my server. Here is the error:
RangeError: Invalid time value
at Date.toISOString ()
Here is the code:
var start = timestamp;
const expiryDate = (new Date(start)).toISOString().split('T')[0];
This exception occurs when the Date object contains an invalid date.
new Date('undefined').toISOString()
In this example the Date object can be created without any problems, but the toISOString function throws an Error.
To fix your issue, you need to make sure that the timestamp variable contains a valid date string.
In my case endDate had a null value:
const [date, setDate] = useState([
{
startDate: new Date(),
endDate: null,
key: "selection",
},
]);
Changing it to new Date() solved the issue:
const [date, setDate] = useState([
{
startDate: new Date(),
endDate: new Date(),
key: "selection",
},
]);
In my case I had previously used JSON.stringify() on an object Task with an attribute duedate of type Date. Consequently taskObj.duedate became a string and did not work as a Date object in my code.
To fix the error, I converted the stringified date to Date type using taskObj.duedate = new Date(taskObj.duedate);