A component in my project is calling a function from another file and passing it an object with three properties: stringProp, numProp, and dateProp (which is a Date object the current component receives as a prop from an input component)
const result = MyAPI.calc({stringProp: {stringProp}, numProp: {numProp}, dateProp: {dateProp}})
console.log(`{stringProp: ${stringProp}, numProp: ${numProp}, dateProp: ${dateProp} ${Object.prototype.toString.call(dateProp)}}`)
// >>> {stringProp: something, numProp: 123, dateProp: Fri Jan 19 2024 [object Date]}
When the calc function is called:
export const calc = (props) =>
{
const stringProp = props.stringProp || ''
const numProp = props.numProp || 0
console.log(`props.dateProp: ${props.dateProp} ${Object.prototype.toString.call(dateProp)}`)
// >>> props.dateProp: [object Object] [object Object]
...
}
numProp and stringProp are coming through as expected, but dateProp is not. These three props were already passed as parameters from one component to another, and came through as expected.
In the original input component, dateProp is saved to state with the useState hook.
I've seen a few similar questions, but not many have been answered, or the solution was to fix a typo which I don't think is the case now.
Update: per @KyleRifqi's answer below, calling JSON.stringify(props.dateProp, null, '\t') will return a value like "2024-01-19T00:00:00.000Z" which shows typeof string. How would I convert this into a date? new Date() does not work and returns Invalid Date. There are a lot of older answers using match and/or a reviver function to convert it, but is there a more modern robust approach?
CodePudding user response:
When an object is converted to a string, it is converted as "[object Object]". If you want to console log an object use the JSON.stringify() function.
Example:
console.log(`props.dateProp: ${JSON.stringify(props.dateProp, null, '\t')}`)
CodePudding user response:
@KyleRifqi's answer led me to find the below approach, which works:
const initializeDate = (dateProp) =>
{
const reviver = (key, value) =>
{
const dateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/
if (typeof value === "string" && dateFormat.test(value))
{
return new Date(value)
}
return value
}
const jsonStringifyDate = JSON.stringify(dateProp, null, '\t')
const revivedDate = JSON.parse(jsonStringifyDate, reviver)
const finalDate = new Date(revivedDate.dateProp)
return finalDate
}
Explanation:
When the calc functions invokes, pass props.dateProp to initializeDate().
jsonStringifyDate:
jsonStringifyDate: {
"dateProp": "2024-01-20T00:00:00.000Z"
}
Attempting to treat jsonStringifyDate as a Date object will not work, as typeof shows its a string.
To convert back to a Date object, use JSON.parse() and pass the reviver function as a second parameter, and transform the parsed value before returning it. revivedDate will be an object.
Access the dateProp property of revivedDate and use that to create a new Date object.
