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

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

exciting, showcasing a dependency map using svg within an html5 environment

I am working on creating a polygon background for my menu, which needs to be responsive in design. Here is an example of what I am trying to achieve: example image. Should I use JavaScript to listen for size changes and adjust the points for the polygon e ...

Leveraging the Google Geocode API through HTTP GET requests

I am facing a challenge in my HTML file where I have a map and I am using HTTP get with jQuery to retrieve a device's location. However, I am struggling to plot this location on the map. I need to parse the location information and display it accurate ...

Tips for updating multiple documents in a MongoDB database using an array of values

I have a range of Product items in my inventory and when a client places an Order, they submit an array of objects. Each object in the array includes the _id product (objectId) and the quantity they purchased. [ {producId: "dshsdsdh72382377923", quantity: ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Utilizing AngularJS to invoke an ng-controller within a nested controller structure

Take a look at this sample code from the cshtml file: <div> <button type="button" ng-click="recalcButton()">Recalc Button</button> </div> <div ng-controller="appealPartialController"> < ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Acquiring information from a variable via an HTTP request

I am new to making http requests and using PHP. I have a code snippet that makes an AJAX call: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc( ...

An issue arises when using JSON.parse() with regular expression values

I am encountering an issue with parsing a JSON string encoded with PHP 5.2 json_encode(). Here is the JSON string: {"foo":"\\."} Although this JSON string is valid according to jsonlint.com, when using the native JSON.parse() method in Chrome a ...

Is there a way to extract the text that lies between two closed HTML

Looking for a solution using jQuery. <pre><marker id="markerStart"></marker> aaaaa <span style='font-family:monospace;background-color:#a0a0a0;'>bbb</span>bb cc<marker id="markerEnd"></marker>ccc </pr ...

Guide on installing React packages during runtime

My React project has a number of packages that need to be installed, but they take up a lot of disk space. I would like to install them only when necessary, after the user interacts with a specific component that requires these packages. Is there a way t ...

What causes an error when attempting ++[] but produces 1 with ++[[]][0]?

Can you explain the difference between the following two expressions? It appears that incrementing [] is equivalent to incrementing [[]][0] since the first element of this outer array is []. console.log(++[]); console.log(++[[]][0]); ...

Converting Milliseconds to a Date using JavaScript

I have been facing a challenge with converting milliseconds data into date format. Despite trying various methods, I found that the solution provided in this link only works for a limited range of milliseconds values and fails for higher values. My goal is ...

What is the best way to store multiple forms in a single request using React?

Is there a more efficient way for me to save multiple forms in multiple child components from the parent component using just one API request? I have attempted to utilize Context and reducer, which did work. However, I am unsure if this is the best approa ...

Jest does not recognize AnimationEvent as a defined element

I am currently facing an issue while attempting to simulate an animationEvent for a test within my Angular application. The error message I receive is: ReferenceError: AnimationEvent is not defined. Given that this feature is experimental, it seems like ...

Utilizing several next.config.js setup files within next.js

I am faced with the requirement for multiple `next.config.js` files (static, prod, dev, etc). How can I manage this situation? Unfortunately, `next build` does not offer a `--config` option and I couldn't locate an environment variable to change the ...

Uploading images dynamically using Ajax and PHP upon submission

Currently, I am working on a modal that submits information and an image through a form to a database using PHP and JavaScript. However, my expertise in JavaScript is limited, so I could use some assistance. So far, I have successfully inserted data from ...

Guide to using AES-256-CBC encryption in Node.js and decrypting with OpenSSL on a Linux system

Question: Hello there, I am currently facing an issue with decrypting my encoded base64 using a specific command. Here is the command that I am trying to use: echo "base64key" | (openssl enc -AES-256-cbc -d -a -pass "pass:test" -pbkdf2 ...