What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux.

How can I resolve this error and convert the timestamp to a date or vice versa?

I need help with valid type conversion methods.

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Timestamp } from 'firebase/firestore';

interface Order {
  dateTime: Date;
  items: {
    item: {
      id: string;
      image: [];
      name: string;
      price: number;
      rating: number;
      uid: string;
    };
    quantity: number;
  }[];
  shopId: string;
  shopName: string;
  status: string;
  uid: string;
  userEmail: string;
}

interface DataState {
  orders: Order[];
}

const initialState: DataState = {
  orders: [],
};


const convertTimestampToDate = (timestamp: any) => {
  const data = timestamp.toDate().toLocaleTimeString('en-US')
  return data
};


export const OrdersSlice = createSlice({
  name: 'OrderState',
  initialState,
  reducers: {
    setOrders: (state, action: PayloadAction<Order[]>) => {
      state.orders = action.payload.map(order => ({
        ...order,
        dateTime: convertTimestampToDate(order.dateTime),
      }));
    },
  },
});

export const { setOrders } = OrdersSlice.actions;

export default OrdersSlice.reducer;

I encountered the following error: Authenticated.tsx:106 A non-serializable value was detected in an action, in the path: payload.0.dateTime. Value: Timestamp {seconds: 1714486856, nanoseconds: 18560000}

Please review the logic that dispatched this action:
{type: 'OrderState/setOrders', payload: Array(1)}

(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) (To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)

Answer №1

Your dateTime property is designed to only accept Date objects:

  dateTime: Date;

Yet, it seems you are currently converting the Firestore timestamp into a string format:

        dateTime: convertTimestampToDate(order.dateTime),


const convertTimestampToDate = (timestamp: any) => {
  const data = timestamp.toDate().toLocaleTimeString('en-US')
  return data
};

The reason for returning a string in the above conversion function is because toLocalTimeString itself returns a string.

Instead of handling strings, it's recommended that you directly convert the timestamp to a Date object and use that as a parameter. Utilize Timestamp.toDate() which gives back a proper Date format:

      state.orders = action.payload.map(order => ({
        ...order,
        dateTime: order.dateTime.toDate(),
      }));

For further reference, check out:

  • How do I convert a Firestore date/Timestamp to a JS Date()?

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

Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered ...

Restrict certain sections of the website to authorized users only

In my game project, players are presented with two options: to play the game itself or to view global and local highscores. I have implemented a signup and login system where upon successful login, users can choose among playing the game, checking highscor ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

How to integrate SCSS into Next.js for enhanced styling capabilities?

editing the issue : __app instead of _app. I'm feeling a bit lost with my current problem. I'm trying to implement SCSS in my React/Next.js application but nothing seems to be working. I have installed the following packages: yarn add node-sas ...

Strategies for Ensuring Ember JS Waits for Asynchronous Functions to Respond Prior to Rendering

Currently, I'm tackling a project that came to the company through an outsourced channel. My query concerns the rendering of an image src. In the past, images were served from the filesystem. However, we've now transitioned to using AWS S3 bucke ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...

I am unable to give back an item

I am working with an object structure that looks like this: const obj = { name: 'john', children: [ { name: 'Foo' }, { name: 'Bar', children: [ { name: 'Doe' ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

Clicking on a Vuetify v-btn with the :href attribute set to download will open the XML file

I'm having trouble getting the v-btn to download an XML file instead of opening it in the browser. <v-btn :disabled="!exportUrl" block x-large height="100" color="primary" :href="exportUrl" download> ...

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...

Tick the checkbox to indicate that I want to insert an image in the adjacent column for the same row

Every time I click on the checkbox, an image should appear in the adjacent column for that specific row. Despite using the addClass() method and targeting the td, the image is appearing in all rows instead of just the selected one. Could somebody help me ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

Exploring the power of intercepting response.send() and response.json() in express.js

Imagine having various instances where response.send(someData) is utilized. What if you wish to implement a universal interceptor that captures all .send functions and modifies someData? Is there a method within express.js to achieve this, such as hooks, ...

Does JSON hijacking play a role with IE versions greater than 10 or Chrome versions greater than 30?

OWASP suggests wrapping json response with an object rather than returning a direct array. For instance: [{"id":5}] Is this vulnerability still relevant? Could it be exploited? After testing in Chrome, IE, and FF, I couldn't find a way to 'h ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

I'm interested in learning about the most efficient practices for handling JSON, performing math operations, and utilizing loops in JS/React. What techniques

Short version: I'm working with a large array of JSON objects (60K+ elements) in my application I need to perform various mathematical operations such as comparison and addition Currently, I am handling this through multiple for loops (simplified ...

Utilize AngularJS to refine and sort through data retrieved from an API

I have an Angular application that is fetching hotel data from an API. I want to filter the results based on the minimum price of the hotels being less than $50. $http.get($rootScope.baseurl + 'api/hotels/', { params: { page_ ...