Error message: The Luxon DateTime was not recognized as a valid Luxon DateTime object

I'm having trouble understanding the workings of Luxon... I'm using Redux Toolkit to initialize the state as shown below

import {DateTime} from "luxon"

interface TestStateProps {
    startDate: DateTime,
    endDate: DateTime,
}

const initialTestState: TestStateProps {
    startDate: DateTime.now(), 
    endDate: DateTime.now(),
}

export const testSlice = createSlice({
    name: 'test',
    initialTestState,
    reducers: {
        addDay: (state, action: PayloadAction<number>) => {
            console.log(state.startDate instanceof DateTime)
            console.log(JSON.stringify(state.startDate))
            console.log(state.startDate.plus({days: action.payload }))
        }
    }
})

The output of the console.log is not what I expected

  1. console.log(state.startDate instanceof DateTime)

false

Why does it return false? I initialized it with DateTime.now()

  1. console.log(JSON.stringify(state.startDate))

{"ts":1724911978667,"_zone":{},"loc":{"locale":"en-DE","numberingSystem":null,"outputCalendar":null,"weekSettings":null,"intl":"en-DE","weekdaysCache":{"format":{},"standalone":{}},"monthsCache":{"format":{},"standalone":{}},"meridiemCache":null,"eraCache":{},"specifiedLocale":null,"fastNumbersCached":null},"invalid":null,"weekData":null,"localWeekData":null,"c":{"year":2024,"month":8,"day":29,"hour":8,"minute":12,"second":58,"millisecond":667},"o":120,"isLuxonDateTime":true}

It seems like the expected result because of "isLuxonDateTime":true. But why is

state.startDate instanceof DateTime
returning false? In the redux dev tools, it doesn't seem to be deserialized or something

https://i.sstatic.net/CbuAS2tr.png

  1. console.log(state.startDate.plus({days: action.payload }))
    eventually throws an error

Uncaught TypeError: state.startDate.plus is not a function

What am I missing here?

Answer №1

I believe the issue lies in Redux Toolkit deserializing the state, leading to potential loss in complex objects (Implementing a custom serializer for different parts of a redux state). The workaround I discovered involves storing dates in milliseconds and converting them when necessary.

import {DateTime} from "luxon"

interface TestStateProps {
    startDateMilliseconds: number,
    endDateMilliseconds: number,
}

const initialTestState: TestStateProps {
    startDate: DateTime.now().toMillis(), 
    endDate: DateTime.now().toMillis(),
}

export const testSlice = createSlice({
    name: 'test',
    initialTestState,
    reducers: {
        addDay: (state, action: PayloadAction<number>) => {
            const startDate = DateTime.fromMillis(state.startDateMilliseconds)
            state.endDateMilliseconds = startDate.plus({days: action.payload}).toMillis()
        }
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA: In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge. I am in the process of retrieving data from a simple query using useQuery along with useResult. The default return type of useResult i ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

Changing an array of objects into nested objects in JavaScript

Currently, I have been assigned the task of organizing the files directory efficiently. All documents and files are stored in a flat array for simplicity. Each file has a uniqueId property that indicates its parent directory. The flat array is sorted based ...

Issue with toggling functionality in Vue.js between two identical components

Within the template of another component, I have two components that can be toggled based on clicks on "reply" and "edit" buttons. <comment-form :model="model" :model-id="modelId" :comment="comment" v-if="showEditForm && canComment" @closeForm= ...

How to resolve the issue of undefined location in React and Next.js?

I'm attempting to send some text based on the hosted URL (where my build is deployed), but I keep encountering this error: ReferenceError: location is not defined Check out my code here. export const getStaticProps = async ({ preview = false, previ ...

The custom modal does not seem to be compatible with the CSS3 animation library,

I managed to create my own Full page modal successfully, but now I want to enhance it with an animation. I am attempting to use animate.css to add animation effects such as zoomIn or zoomOut, but it's not working as expected. Here is the link to my J ...

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

Limiting the size of image uploads in AWS S3

Currently, I am attempting to go through the steps outlined in this repo, which involves utilizing nextjs and AWS S3 for image uploading. However, one thing that is puzzling me is the limitation of 1MB on image sizes. I'm curious as to why this restri ...

Updating ngRepeat Array Data in AngularJS using Events

I'm currently in the process of transitioning my jQuery application to AngularJS. One of the tasks I need to accomplish involves updating the Data Array whenever a scroll event occurs. How can I achieve this? Here is the existing jQuery code at Plun ...

What's the best way to align this text and icon next to each other?

I have text and an icon that are currently displaying far apart. How can I align the icon to the right of the text like shown below: Water Jug-> For reference, here is the link to a Codesandbox demonstration: https://codesandbox.io/s/responsivestack-ma ...

Unleashing the Power of JavaScript to Boost Page Performance

I've created a page using Vue.js 2 and Jquery, but it's running very slowly. I'm really struggling to optimize its performance. Could any experts out there help me with some ideas on how to speed it up? Thank you in advance. Here is the lin ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Unable to scroll horizontally beyond 200 viewport widths

I'm facing an issue with my code that switches between vertical and horizontal scrolling but seems to have a width limit of 200vw. When I set the min-width to 50vw, only 4 sections are visible, whereas setting it to 100vw (as shown in the example) dis ...

What is the best method to combine two BufferGeometries into a single BufferGeometry using Three.JS?

Wondering how to combine two buffer geometries into a single THREE.BufferGeometry in ThreeJS? var mergedGeometry = null; geometry = new THREE.CylinderGeometry(10, 10, 10); if (mergedGeometry === null) { mergedGeometry = new THREE.BufferGeometry().fr ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

Challenges arise with the height settings of ui-grid

Currently, I am facing an issue with using height: auto on an angularJS ui-grid. The problem arises from an inline style that specifies a fixed height on the div to which the ui-grid attribute is added. Additionally, the function getViewPortStyle() dynamic ...

Managing DateTime data type between C# and PHP using SOAP web services

In my work, I handle web services implemented in C# and PHP on the client side. When using SOAP __getTypes, it indicates that one of the expected parameters should be a dateTime birthDate. I attempted to send the parameter in various formats, such as $da ...

Tips on effectively rendering child components conditionally in React

My components currently consist of an AddBookPanel containing the AddBookForm. I am looking to implement a feature where the form is displayed upon clicking the 'AddBookButton', and hidden when the 'x' button (image within AddBookForm c ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...