Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Format Date in GraphQL in Gatsby Site

I am having trouble formatting a date in Gatsby. I have sourced some data from firestore. One of the fields that I have sourced is called datePublished and it contains a number in the form of a timestamp (e.g., 1576945502000). Indeed, it really is a timestamp, but it got saved to firestore in the number format type.

Now, I would like to format the datePublished field using the formatString function in graphql -- as noted here: https://www.gatsbyjs.org/docs/graphql-reference/#dates

But I can't get the formatting to work. Whether I try to format the string in graphiql or on my site, it does not work. Here is the code that I tried:

query MyQuery {
  allNewsFeed {
    edges {
      node {
        published(formatString:"dddd Mo, YYYY")
      }
    }
  }
}

And this is the error message that I get in graphiql:

Unknown argument "formatString on field 'datePublished' of type 'NewsFeed'.

If I dig a little deeper, I notice that the field type in firestore is listed as number and in the graphiql document explorer it is listed as a FloatQueryOperatorInput.

What's more, I did a little experiment where I tried to save the same number as a string, number and timestamp in firestore. Neither the string or number format worked and for whatever reason, the gatsby-firesource plugin will not pull in the field with a timestamp format.

So I am wondering, what do I have to do to get this to work in gatsby?

Any ideas?

Thanks.

like image 904
Moshe Avatar asked Nov 07 '22 11:11

Moshe


1 Answers

I had a similar situation with Gatsby not accepting "formatString" on a date field, for me what solved the issue was to change the format of the field to YYYY-MM-DD so it went from 02 06 2017 to 2017-06-02 and gatsby got the hint that that field represents a date. It seems gatsby "reads" the data and guesses the type and based on that we get certain functionality.

Since gatsby uses moment.js I'm guessing the YYYY-MM-DD format is picked up by it.

I'm using MDX so it was really easy for me to change the format of my date field since it's just plain text, I'm not sure you have the same luxury with firestore but I hope this at least give you some ideas to try out. Good luck!

like image 134
Bojan Gvozderac Avatar answered Nov 13 '22 03:11

Bojan Gvozderac