Axios post request in Gatsbyjs

Viewed 3989

I have blogsite using gatsbyjs template and I have a newsletter feature which is sending the user's email. so basically Im using axios post request in sending emails.

Im wondering if the axios will work perfectly fine in gatsby in live site after build? Isnt the gatsby is building a static files? does the axios still work?

2 Answers

Yes, it will work, you have many axios examples across Gatsby's docs.

Gatsby generates JS files, so executing axios code won't be a problem.

Of course, it will work, Gatsby generates and compiles all files when you deploy it (or running the build command); this means that it takes the content (and data) from all sources (using GraphQL) and generates a static HTML file with a bundled JavaScript file, which doesn't mean that you cannot have asynchronous data fetching or asynchronous functions to do whatever you do. It's just a page-generation.

Afterward, if you want to load asynchronously all your content with Axios (for example), you are capable to achieve this, however, you will be losing the potential of Gatsby. Indeed, your site will be a React-based site so you have all that Gatsby offers in terms of page generation + React features.

So, all your JavaScript functions will trigger when you want (onClick, useEffect, componentDidMount, etc). Here's a screenshot about how Gatsby works in terms of data fetching.

enter image description here

The only thing you need to take into account is when using third-party libraries to not load into your Webpack configuration (because some libraries need the window to be defined at the build time, and with Gatsby, you don't) but it is perfectly handled in their documentation.

Related