The error message states that there is a problem with the function task.dueDate.toDate,

I am currently utilizing Firebase as my database along with Next.js. I have encountered an issue when trying to read data from Firebase, specifically related to the due date field, which is of timestamp datatype. Here is the code snippet where I attempt to retrieve data from Firebase:

const dbInstance = collection(firestore, "tasks");
useEffect(() => {
  getTasks();
}, []);

const getTasks = () => {
  getDocs(dbInstance).then((data) => {
    setTasksArray(
      data.docs.map((item) => {
        return { ...item.data() };
      })
    );
  });
};

While iterating through all tasks in the tasks array, everything worked smoothly except for the due date. Upon researching a solution, I came across the toDate() function. When I tried task.duedate.toDate(), an error was triggered.

The approach that yielded some results for me is as follows:

{tasksArray.map((task) => {
  return (
    <Flex
      flexDir={"column"}
      key={task.creatorId}
      hidden={task.priority != "" ? true : false}
    >
      <Text>{task.taskName}</Text>
      <Text fontSize="xs">
        {safeJsonStringify(task.dueDate)}
      </Text>
    </Flex>
  );
})}

While this displayed: {"seconds":1683300279,"nanoseconds":338000000}

I aim to present it in a more user-friendly manner similar to how it appears here on Stack Overflow.

Answer №1

Presumptions

After analyzing the most recent data, it is presumed that the dueDate field is structured as a JavaScript Object rather than being an instance of Firebase Timestamp. The format of this object is similar to:

{
  seconds: 1683300279, 
  nanoseconds:338000000
}

If we consider it as an Object, there is no inherent method like .toDate. Based on these presumptions, here are two suggested solutions:

1. Creating a Firebase Timestamp from the Object

const timestamp = new firebase.firestore.Timestamp(dueDate.seconds, dueDate.nanoseconds)

This will create an actual Timestamp object with access to the .toDate method.

2. Converting JS Object to Date using time calculations

In JavaScript, the new Date() constructor accepts milliseconds.

You can convert the object's data into milliseconds and then construct a JS Date by following these steps:

const NS_TO_MS_MULTIPLIER = 1/1000000
const SEC_TO_MS_MULTIPLIER = 1000

const timestampInMilliseconds = dueDate.seconds * SEC_TO_MS_MULTIPLIER + dueDate.nanoseconds * NS_TO_MS_MULTIPLIER

// Using the total milliseconds value to create a Date object
const date = new Date(timestampInMilliseconds)

Both methods have been demonstrated in a CodeSandbox example: https://codesandbox.io/s/infallible-khayyam-68iw0p?file=/src/App.js

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

Empty text box

I've been attempting to clear ng-model inputs, but haven't had any success and I can't seem to figure out why. Here is what I have: <button ng-click="$ctrl.clear()"></button> And in the clear action, I have: $scope.$event = n ...

Issues with jQuery function arising post-update to newer jQuery version

Recently, I encountered an issue with a function that used to work perfectly fine with jQuery 1.8.3. However, when I upgraded to jQuery 1.10.x or above, the function stopped working. <script type="text/javascript"> $.ajaxSetup({cache: false}); ...

jQuery random generator for creating two-dimensional arrays

Why do all rows always have the same numbers? They should be populated with random numbers. Also, how can I fix this issue? I remember seeing a solution here before but now I can't seem to locate it. var mapSizex = 5; var mapSizey = 6; var mapArray ...

Creating a streamlined real-time application using the powerful combination of Django-swampdragon and AngularJS

Currently, I am using django-swampdragon along with angularjs to develop a simple Django application that displays website requests in real-time. While the Django part of the logic seems to be functioning correctly, I encounter issues when attempting to m ...

What is the best way to add HTML content to a specific div element within an AJAX call's success function?

In the provided ajax script, my goal is to insert HTML content into a specific div element inside a table. The main div element in question is named "ajaxcom", but I need to insert the HTML content into a div element with the class = "divrep". How can I ac ...

Is it possible to use both "npm install --global" and "--save" simultaneously?

I'm curious if it is practical to use both the --global and --save parameters in the npm install command simultaneously. For instance: npm install gulp -g -s From my understanding, since there is no package.json in the npm system folder, I assume th ...

What is the best way to incorporate a listener into an Angular directive?

I have a custom directive that generates a dynamic Google chart. My goal is to activate an event handler on the controller's scope whenever the directive detects an event from the chart. For example: http://plnkr.co/edit/yn4KuQfrYvlQNbPSWk3Q?p=previe ...

Whenever I attempt to populate my modal box with data from my selection, I am greeted with an error message stating "invalid object passed in." What could be causing this issue?

Whenever I click on a customer from my table to display their details in a modal box, I keep getting an error message that says "invalid object passed in." The method client is responsible for populating the data and displaying it through a partial view. T ...

How can I prevent the browser's back button from functioning on an AngularJS webpage?

Is there a way to disable the browser's back button and refresh button in Angular? For example, in my source code: Page Source: "use strict"; .controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) { $scope.$on ...

What could be causing the Opera browser to send an excessive amount of "MessageEvent" messages through Nextjs in the console?

I have been a dedicated user of Firefox for programming my entire life, but recently I decided to give Opera a try due to its interesting features. However, I am becoming increasingly frustrated with the excessive spamming of the "MessageEvent" console. Is ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Is it possible to incorporate button classes from the <a> tag into a JQuery fade in/fade out function?

My jQuery image thumb Slider features thumb buttons that link to different div elements. When a user clicks on a thumb button, I want the associated div to smoothly fade in, replacing the previous one. The goal is to have a seamless transition between the ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...

Exploring deep within JSON data using jQuery or Javascript

I have a substantial JSON file with nested data that I utilize to populate a treeview. My goal is to search through this treeview's data using text input and retrieve all matching nodes along with their parent nodes to maintain the structure of the tr ...

Designing architecture for NPM packages in TypeScript

I am currently developing multiple NPM packages using TypeScript and I am exploring the most effective strategies for supporting various target architectures. When compiling to ES3, there is extensive support but it comes with additional boilerplate for c ...

Please incorporate the href attribute into the anchor tag when it is clicked

<section> <a **id="download"** oncontextmenu="return false" > <svg ... </svg></a> </section> <script type="text/javascript"> The following code snippet is designed to ...

What is the best way to incorporate a JSON file into a JavaScript class?

I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function. class CreatePage { constructor() { var request = new XMLHttpRequest(); request. ...

The express-unless plugin in Node.js allows you to exclude specific paths from the middleware.auth

I need help implementing express-unless to exclude a /health path from using middleware.auth. Unfortunately, I am facing syntax issues and unable to test this locally. Using localSite == true is not compatible with my environment. The error logs are shown ...

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...