Dynamic date selected and current month is not displayed - reactjs

This is my problem link
I am passing dynamic date array and getting month based on the current date but it is not working.
This is reference link

You need to pass an array instead of function call in selectedDays and you are passing date parameter wrong in selectedDaysS function :
selectedDaysS = daysArr => {
let dataToSend = daysArr.map(a => {
let m = a.split('-');
return new Date(m[0], m[1], m[2]);
});
return dataToSend;
};
and inside render :
return (
<DayPicker
initialMonth={this.currentMonth()}
selectedDays={this.selectedDaysS(["2019-07-25"])}
/>
);
Here is live link : https://codesandbox.io/s/react-day-picker-examplesselected-nfbgz?fontsize=14

Related

React - convert date with date-fns

I have a date in this format: 12-21-2021
This date comes from a Redux selector.
So console.log('ccc', lastUpdateDate); at the beginning shows only:
ccc
and after few times shows
ccc 12-21-202
If I use new Date(lastUpdateDate).toDateString() it turns out it works only in Chrome, whereas FireFox and Safari say this is an invalid date.
So I want to convert it in the right way using a function.
So I created this function:
const parseDateWithDashes = (dateToParse) => {
console.log('dateToParse', dateToParse);
useEffect((): any => {
let finalDate;
dateToParse instanceof Date && dateToParse.getTime()
? (finalDate = format(dateToParse, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"))
: null;
console.log('finalDate', finalDate);
return finalDate;
}, [dateToParse]); //since at the beginning it is empty, it should re-run as a date is available
};
parseDateWithDashes(lastUpdateDate)
However doing this it logs out:
dateToParse (several time empty)
dateToParse 12-21-2021
finalDate undefined (several times)
I've also tried to run the function in a useEffect...
useEffect(() => {
parseDateWithDashes(lastUpdateDate);
});
But that's an invalid hook call.
What am I doing wrong? How to fix that?
I resolved it this way.
I added the parsing to the thunk. And stringified in order to avoid non-serialized errors:
const parsedDate = parse(lastUpdateDate, 'MM-dd-yyyy', new Date());
dispatch(setLastUpdateDate(JSON.stringify(parsedDate)));
Then I just formatted it in the component:
export const convertStringDateToDate = (date: string) => {
let finalDate;
try {
finalDate = JSON.parse(date);
finalDate = format(parseISO(finalDate), 'E LLL d yyyy');
} catch (e) {
finalDate = 'loading date';
}
return finalDate;
};
That works

Rendering Date from model in react

I am trying to get the date to render in a nice format. currently rendering like this
I tried
function getEndDateFromstring(){
return itinerary.endDate.split('T').slice(-1)[0]
}
then
{itinerary.name} from {getStartDateFromstring()} to {getEndDateFromstring()}
But it is throwing an error
Uncaught TypeError: Cannot read properties of undefined (reading 'split')
This looks like a scope issue, pass the itinerary to your function like below
function getEndDateFromstring(itinerary){
return itinerary.endDate.split('T').slice(-1)[0]
}
and call like
{itinerary.name} from {getStartDateFromstring(itinerary)} to {getEndDateFromstring(itinerary)}
I got it working with this
function addZeroIfOnlyOneChar(dateString){
dateString = String(dateString);
if(dateString.length < 2){
return '0' + dateString
}
return dateString
}
function getDateFromString(dateString){
const date = new Date(dateString)
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${addZeroIfOnlyOneChar(day)}-${addZeroIfOnlyOneChar(month)}-${year}`
}
Thanks Everyone

Creating a reusable date formatter in React

I've been struggling to create a reusable function that I can call on dates in my data. The goal is to take any date given, determine if it has just a date, or date and time, then return the data in the appropriate format.
I've been using moment to format things, but am not sure how to actually call this function on the data. I'm very new to React
Here is what I've got so far:
import moment from "moment";
const FormatDate = (dateObject) => {
var dateMutant = dateObject;
var dateMutated = "";
function justDate() {
//formats just a date
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY");
}
function dateTime() {
//formats a date and time
dateMutated = moment.utc(dateMutant).format("MM-DD-YYYY hh:mm:a");
}
console.log(dateMutated);
return dateMutated;
};
export default FormatDate
I am attempting to call it in a page like this:
React.useEffect(() => {
var testDate = '';
if (allCommentsFetch) {
setAllCommentsLoading(true);
axios
.get(`###API Hook##`)
.then(response => {
let comments = response.data;
comments.forEach(commentfield => {
if (commentfield != null) {
commentfield['commentTimestamp'] = moment.utc(commentfield.commentTimestamp).format('YYYY-MM-DD hh:mm:ss');
testDate = FormatDate(commentfield.commentTimestamp).justDate();
} else {
comments[commentfield] = 'N/A'
}
})
but am getting an error that Object(...)(...).justDate is not a function.
you can write it in a better and cleaner way, first of all, you have not to write your module names in PascalCase, getFormattedName will be a better choice! the second thing is that you are using var... avoid that.
the only thing you have to change in the format function is a format template... and as i see you have only two option (justDate and dateTime) in this case, so let's write it again:
const getFormattedDate = ({ dateObject, includeTime }) => {
const dateFormat = includeTime ? 'MM-DD-YYYY hh:mm:a' : 'MM-DD-YYYY';
return moment.utc(dateObject).format(dateFormat);
};
and about the error you got: (but am getting an error that Object(...)(...).justDate is not a function) the problem is that you didn't return justDate from the FormatDate function.

React : Pushing result of map() to an array

Hello I am trying to map through an array of objects and push them to a new array.
My ISSUE : only the last item of the object is being pushed to the new array
I believe this has to do with React life cycle methods but I don't know where I should I loop and push the values to the array to get the full list
//My object in an array named states
var states = [{"_id":"Virginia","name":"Virginia","abbreviation":"VN","__v":0},{"_id":"North Carolina","name":"North Carolina","abbreviation":"NC","__v":0},{"_id":"California","name":"California","abbreviation":"CA","__v":0}];
export function StateSelect()
{
**EDIT 1**
const options = [];
function getStates()
{
//This is how I am looping through it and adding to an array
{ states.length > 0 &&
states.map(item =>
(
console.log(`ITEM: ${JSON.stringify(item)}`),
options.push([{ value: `${item.name}`, label: `${item.name}`}])
))
}
}
return( {getStates()}: );
}
Thank you
It looks like your getStates() might not even be returning anything... but assuming it is, I believe you should be able to accomplish this using a forEach() fn in order to push values into your options array... Try adding the following into your map:
states.map((item) => {
console.log(`ITEM: ${JSON.stringify(item)}`);
let processed = 0;
item.forEach((i) => {
options.push([{ value: `${i.name}`, label: `${i.name}`}]);
processed++;
if(processed === item.length) {
// callback fn, or return
}
}
.map usually used to return another result, you could just use .forEach
In fact, you don't really need to declare options at all, just use .map on state to return the result would be fine.
return states.length > 0 && states.map(({ name }) => {
return { value: name, label: name };
});

setState not working in React JS

I am trying to give few dates to state.periods array. But it is not working. My code is as follows.
class SmallTable extends Component {
constructor(props) {
super(props);
console.log(props.startDate)
this.state = {
turns: [],
periods: []
}
}
componentDidMount() {
//calculate years/ months and keep in one array
const today = new Date();
var periods1 = [];
if (this.props.period=="year") { //if year calculate from last year last date
const lastYearLastDate= new Date(new Date().getFullYear()-1, 11, 31)
periods1.push(lastYearLastDate.getFullYear()+"-"+(lastYearLastDate.getMonth()+1)+"-"+lastYearLastDate.getDate());
var lastYearFirstDate= new Date(lastYearLastDate.getFullYear()-1,0,1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastYearFirstDate.getFullYear()+"-"+(lastYearFirstDate.getMonth()+1)+"-"+lastYearFirstDate.getDate());
lastYearFirstDate = new Date(lastYearFirstDate.getFullYear()-1,0,1);
}
}
else if (this.props.period=="month") {//if month calculate from last month last date
var d=new Date(); // current date
d.setDate(1); // going to 1st of the month
d.setHours(-1); // going to last hour before this date even started.
var lastMonthLastDate = d;
periods1.push(lastMonthLastDate.getFullYear()+"-"+(lastMonthLastDate.getMonth()+1)+"-"+lastMonthLastDate.getDate());
//go to last month first date
var lastMonthFirstDate = new Date(lastMonthLastDate.getFullYear(), lastMonthLastDate.getMonth(),1);
//for the remaining periods
for (var i=0;i<this.props.numberOfPeriods-1;i++) {
periods1.push(lastMonthFirstDate.getFullYear()+"-"+(lastMonthFirstDate.getMonth()+1)+"-"+lastMonthFirstDate.getDate());
lastMonthFirstDate=new Date(lastMonthFirstDate.getFullYear(), lastMonthFirstDate.getMonth()-1,1);
}
}
console.log(periods1); -->prints ["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]
this.setState((prevState)=>{
return {
periods: prevState.periods.push(periods1)
}
});
console.log(this.state.periods) --> prints []
}
render() {
return ( <div></div>)
}
How to get values in periods1 to periods state. I am trying to insert periods1 array into state periods array. Those are strings. Pls suggest where the error might be.
You're setting this.state.periods to the result of a push operation. But push returns the new array length, not the array itself. Try this instead:
periods: [...prevState.periods, periods1]
push() doesn't return a value.
You should use:
this.setState((prevState)=>{
let old = prevState.periods.slice();
old.push(periods1);
return {
periods: old
}
});
You have a few issues.
For the code here:
return {
periods: prevState.periods.push(periods1)
}
You never want to mutate state. Instead, you should create a new array object and then add the data, like so:
return {
periods: prevState.periods.concat([periods1])
}
Secondly, your console.log is in the wrong place
console.log(this.state.periods) --> prints []
setState happens asynchronously and thus may not finish by the time your componentDidMount method returns. Instead, put that console.log inside your render function to see the new state.
If you expect this.state.periods to be an array of arrays ([["2017-12-31", "2016-1-1", "2015-1-1", "2014-1-1"]]) you can push your array following an immutable pattern using the spread operator :
this.setState((prevState) => ({
periods: [...prevState.periods, periods1]
}), () => { console.log(this.state.periods) } );
You can notice the function passed as second param of setState() is a callback to execute console.log() after the state update.
If you want to push periods1 values in this.state.periods you can do this :
this.setState((prevState) => ({
periods: [...prevState.periods, ...periods1]
}));
Try to make a copy of your original state, so that you can perform setState in an immutable fashion.
const periods = [...this.state.periods];
periods.push(periods1);
this.setState({periods: periods});

Resources