<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Richard Lööf on Medium]]></title>
        <description><![CDATA[Stories by Richard Lööf on Medium]]></description>
        <link>https://medium.com/@richardl?source=rss-83401b501628------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rvx6LTktLp8tyHlY1KgxtQ.jpeg</url>
            <title>Stories by Richard Lööf on Medium</title>
            <link>https://medium.com/@richardl?source=rss-83401b501628------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:41:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@richardl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create a webshop in Gatsby JS]]></title>
            <link>https://medium.com/@richardl/how-to-create-a-webshop-in-gatsby-js-44fe0b88310e?source=rss-83401b501628------2</link>
            <guid isPermaLink="false">https://medium.com/p/44fe0b88310e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webshop]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gatsby]]></category>
            <dc:creator><![CDATA[Richard Lööf]]></dc:creator>
            <pubDate>Tue, 14 May 2019 08:23:46 GMT</pubDate>
            <atom:updated>2019-05-14T08:23:46.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I held a talk at the Stockholm ReactJS Meetup on how to add more dynamic elements to your Gatsby-sites, showcasing that a Gatsby site is not just a static landing page. As an example, I showed how to create a simple webshop with Gatsby. This is a blog-post on the same topic, with some included code samples.</p><p>I’ll be focusing specifically on building a webshop, skipping past some more general parts of Gatsby. If you’d like a great getting started tutorial have a look at the official one <a href="https://www.gatsbyjs.org/tutorial">here</a>. I’ll be making references to parts of it below.</p><p>I will also skip past the standard, classic parts, of building a webshop application in order to focus on the few important things needed to make this work in Gatsby. If you’d like to see all of the code in its entirety or clone the app to try it out yourself I’ve created a repo for it on <a href="https://github.com/richardloof/gatsby-webshop-example">Github</a>.</p><p>Let’s get started!</p><h3>Creating the products</h3><p>First out is creating the products. Our simple webshop will have one page for listing all of the products and an individual page for each individual product (on which you would normally have some more detailed info for the specific product). The products will most probably live on a backend server or in a CMS.</p><p>The following two pictures display the structure of the site. Btw I’ve based my example app on the gatsby-material-ui-starter in order to get some quick styling up. If you want to check that starter out it’s also on Github <a href="https://github.com/nareshbhatia/gatsby-starter-material-ui">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7uGkLrD1Mg-Sq9WvDmylA.png" /><figcaption>A screenshot of our index page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nl5cKosHLrqHzd5PZ9OdaQ.png" /><figcaption>And a screenshot of a product’s specific page. (Sorry about the cat images, finding seed data is hard..)</figcaption></figure><p>If you have any previous experience with Gatsby you know that there are many different ways to fetch data for your application by making use of one of the plugins provided by the community. See parts <a href="https://www.gatsbyjs.org/tutorial/part-four/">4</a> and <a href="https://www.gatsbyjs.org/tutorial/part-five/">5</a> in the Gatsby tutorial.</p><p>For this example I’ve mocked the backend data by creating a simple JSON-file like this:</p><pre>[<br>  {<br>    “id”: “1”,<br>    “title”: “Baseball bat”,<br>    “description”: “Knock it out of the park!”,<br>    “price”: 500,<br>    “imageUrl”: “https://loremflickr.com/320/240?lock=1&quot;<br>  },<br>  {<br>    “id”: “2”,<br>    “title”: “Football”,<br>    “description”: “Best football on the market right now”,<br>    “price”: 3900,<br>    “imageUrl”: “https://loremflickr.com/320/240?lock=2&quot;<br>  }<br>  // And so forth.. (other products omitted for brevity)<br>]</pre><h4>Programmatically creating pages</h4><p>The most interesting part now is to figure out how to programmatically create pages from data at build time. We want to be able to fetch all products from our backend of choice and then have Gatsby automatically create a page for each one. This can be accomplished by making use of the <a href="https://www.gatsbyjs.org/docs/node-apis/#createPages">createPages-api</a> within gatsby-node.js.</p><p>In my example I’m using the gatsby-source-filesystem plugin in order to demonstrate how this would look like when querying an external api. Even though in this case I could have just imported the data by requiring the module like this (since it lives in a plain JSON-file):</p><pre>products = require(&#39;./data/products.json&#39;);</pre><p>The more realistic implementation including a graphql-call to fetch the products now looks like this:</p><pre>// gatsby-node.js</pre><pre>const path = require(&#39;path&#39;);<br>// A function to build our mock backend graphql-query<br>const allProductsJson = require(&#39;./graphql/all-products-gql&#39;).query;</pre><pre>exports.createPages = async ({ actions, graphql }) =&gt; {<br>  const { createPage } = actions;</pre><pre>  const products = await graphql(allProductsJson()).then(result =&gt; {<br>    if (result.errors) throw result.errors;<br>    const productNodes = result.data.allProductsJson.edges;</pre><pre>    return productNodes.map(edge =&gt; {<br>      return {<br>        ...edge.node<br>      };<br>    });<br>  });</pre><pre>  createPage({<br>    path: &#39;/&#39;,<br>    component: path.resolve(&#39;./src/templates/index-page.js&#39;),<br>    context: {<br>      products<br>    }<br>  });</pre><pre>  products.forEach(product =&gt; {<br>    createPage({<br>      path: `/product/${product.id}`,<br>      component: path.resolve(&#39;./src/templates/product-page.js&#39;),<br>      context: {<br>        product<br>      }<br>    });<br>  });<br>};</pre><p>The createPages-api is a function called with a JS-object containing a collection of helpers and lifecycle methods exposed from Gatsby that you can use. In this case, we are interested in actions and graphql specifically.</p><h4>Our process looks like this</h4><ol><li>Fetch all products by making the proper graphql-call</li><li>Call the actions.createPage-function with a template for the index-page and pass all products as a prop into pageContext</li><li>Loop over all products and create a specific page for each one based on the product-page template, with a custom route and pass the product as a prop into pageContext</li></ol><p>The ability to create pages programmatically like this is pretty cool when you first discover it. If you haven’t used it before and just got curious, have a look at <a href="https://www.gatsbyjs.org/tutorial/part-seven/">part 7</a> of the Gatsby tutorial.</p><h3>Creating the shopping cart</h3><p>As you saw in the previous screenshots there was a hovering button with a cart icon in the lower-right corner of the screen. In this part we’ll implement the functionality to add and remove products from the cart, and also to see the contents of it. When we’re done the cart page will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dvN8dJV1ZYcZ9UmnK0_vw.png" /><figcaption>This view is where you’ll get to when clicking the cart button</figcaption></figure><p>Since every page in Gatsby will be built as a separate page (as opposed to a classic SPA written in React where the entire application is baked into one big JS-file) we need to save the state in localStorage in order for us to persist the Redux-state between page navigations. In this app, I’m using <a href="https://github.com/rt2zz/redux-persist">redux-persist</a>. A really nice package which includes state reconciliations, schema migrations and many other useful features for dealing with client-side storage.</p><p>The first step is adding the middleware when creating your root reducer. We’ll use this in our app by setting up a standard ReduxProvider-component. If you haven’t used redux-persist before you’ll notice that we’ve added a PersistGate-wrapper inside the standard Provider one. For more information on how to set up redux-persist, check out their repo (they have good docs) or the implementation in my code sample.</p><pre>// redux-provider-wrapper/index.js</pre><pre>import React from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import { PersistGate } from &#39;redux-persist/integration/react&#39;;</pre><pre>import { store, persistor } from &#39;./persisted-store&#39;;</pre><pre>export default function ReduxWrapper({ element }) {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;PersistGate loading={null} persistor={persistor}&gt;<br>        {element}<br>      &lt;/PersistGate&gt;<br>    &lt;/Provider&gt;<br>  );<br>}</pre><pre>ReduxWrapper.propTypes = {<br>  element: PropTypes.node,<br>};</pre><p>After this, you’ll need to wrap all of your pages in our new ReduxProvider. This can be done by exporting your ReduxProvider component as the named export wrapRootElement in gatbsy-browser.js and gatsby-ssr.js. This will automatically wrap all of the pages of your app in the specified component.</p><pre>// gatsby-browser.js<br>// gatsby-ssr.js<br>// (They&#39;ll both have this same export)</pre><pre>const ReduxWrapper = require(&#39;./redux-provider-wrapper&#39;).default;</pre><pre>exports.wrapRootElement = ReduxWrapper;</pre><p>Now we have a fully functioning shopping cart! You can add and remove products from the cart and it will persist the current state of the cart across page navigations (or even when closing the page since it’s stored in localStorage).</p><p>Don’t forget to make a migration if you ever change the shape of your Redux-state, otherwise, you’ll have invalid data (a mix of the old and the new schema) on the client. This will likely cause exceptions when dispatching actions to the store or when calling selectors. If you ever were to forget making a migration or by accident make an invalid one you can always clear out the user’s local copy of the store by creating a migration like this:</p><pre>{<br>  ...previousMigrationsGoHere,<br>  3: () =&gt; {}<br>}</pre><p>Where 3 is the version number. Pick whatever version you’re on.</p><h3>Further improvements</h3><p>This was an example of how to get started with building the basic flow of a webshop in Gatsby JS. A few possible features to add would be:</p><ol><li>Add a checkout feature<br>You have access to the native fetch API from within your React components. Send off a request to your backend of choice and start the delivery process.</li><li>Logging in users<br>This is an exciting one. Since logging in users comes down to storing a token of some sort in localStorage you can quickly see how this is also feasible to do in Gatsby by using the same strategy as we did for persisting our cart. There even is an official tutorial on how to do it <a href="https://www.gatsbyjs.org/docs/authentication-tutorial/">here</a>!</li></ol><p>Adding the ability to sign in users would unlock the possibility of many cool features to really make this site a full-fledged webshop. For example logging in to view the status of your past orders, request returns and so on.</p><h3>Rounding up</h3><p>I’d like to thank everyone who came to Stockholm ReactJS last Monday and listened to me and the rest of the speakers. As always it was very inspiring chatting with lots of talented developers and I’m looking forward to hearing more about all the exciting things people are building at the next event!</p><p>If you’d like to work with the latest technology and together with a whole bunch of very smart and dedicated people, please check out our career page at <a href="https://careers.universalavenue.com/">Universal Avenue</a>.</p><p>Until next time!</p><p><em>Connect with me on social media:<br></em><a href="https://twitter.com/richardloof"><em>Twitter</em></a><em> | </em><a href="https://www.instagram.com/richard.loof/"><em>Instagram</em></a><em> | </em><a href="https://www.linkedin.com/in/richard-l%C3%B6%C3%B6f-902b1070/"><em>LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44fe0b88310e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>