Build a Product Recommendation Quiz App with Shopify, Gadget, and Vercel
Tags: javascript, react, devrel, writing
Published: 2022-04-22 14:01:20

_Time to build: approx. 1 hour_

**Technical Requirements**

To get the most out of this tutorial, you will need:

- A Shopify Partner account and a connected test store with the online store channel and a recently-installed Shopify-developed theme;
- A reasonable familiarity with Shopify online store themes and are comfortable navigating theme architecture;
- Comfort with Next.js, React, and Javascript

## Introduction

Product recommendation quizzes are a powerful tool to build engaging sales experiences for shoppers on online stores by allowing them to map their problems or concerns to a product that best meets their needs. For Shopify merchants, this can be an appealing proposition – with an app that lets them build dynamic quizzes, they can present their shoppers with a tailored experience that can result in more conversions and higher satisfaction by matching the right shopper with the right products.

In under an hour, we can create a lightweight, customizable product recommendation quiz app using Gadget, connect the results to products in a Shopify merchant's store, and build both an embedded in-theme quiz and a stand-alone quiz web application hosted on Vercel. This app will allow a merchant to create quizzes quickly and then serve a quiz or quizzes to their shoppers wherever they may be.

In our example, we will build a product recommendation quiz that recommends the appropriate skincare bundle from four options based on the shopper's answers. We can also configure the app to track the conversion state of each response to any quiz, giving the merchant rich information about the effectiveness of their quiz or quizzes.

### Proposed Solution Design

We need a way to create, serve, and record quiz responses in our app. The recording of responses enables us to track the conversion state we discussed above, effectively making a response to a quiz a snapshot of a session that a shopper has with our quiz. Going forward, to distinguish between the models and the concepts they represent, we'll refer to the models in the title case (e.g. a Result model vs result in reference to an outcome).

In terms of object relationships, a Quiz itself has one-to-many Questions, and each Question can have one-to-many Answers. As an instance of _taking_ the Quiz, a Response belongs to a Quiz, has one-to-many Answers, and has one Result based on the selected Answers.

But how do the Answers lead to a Result? We can build a mapping interface to allow us to select which Answers link to which Result as a part of our app's admin UI

Here's a diagram to demonstrate what relationships our models will have with each other:


![Model Relationship Diagram for our App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t60b9scup7721ueesz2p.png)

Let's build!

## Getting Started with Gadget
### What is Gadget?

[Gadget](https://gadget.dev) is a tool that allows developers to build and run a robust backend quickly by reducing the menial, repetitive work involved in building software, freeing you up to focus your time on business logic, not boilerplate.

From hosted database to CRUD and custom API endpoints, Gadget provides you with simple, yet powerful building blocks that you can leverage to save time.

Gadget is in open beta right now, and is free to try. 

### Who is Gadget for? 

**Gadget is for developers who want to ship fast.** If you find yourself frustrated by building the same features over and over, or spending more of your time on glue code as opposed to what matters, then Gadget is for you.

**Gadget is for people who like to code.** While Gadget has artfully reduced the need to write endless code through our abstraction, Gadget still believes that coding is the best way to express complex business logic. So you will still code in Gadget, just not as much.

### What Gadget gives you

Gadget is a full featured application development platform with many tools, features, and integrations that help you build things quickly. Here's what Gadget gives you:

- A place to store data
- A place to run back-end JavaScript code
- A shuttle for data in other systems, like Shopify
- A rich API and API Client, and auto-generated documentation
- A place to store images and other files
- A high performance expression language, Gelly
- An authentication system
- A secure environment, and
- Hosting and a URL


### Starting your app

Head over to [app.gadget.dev](https://app.gadget.dev) and authenticate with Google, Github, or create/log in to your account. Next, Gadget will prompt you to create a new application. Click “Create App,” and Gadget will bring you into your new application.

## Connecting to Shopify

To recommend products to shoppers, we'll need product data in our app that we can map to the results of a product recommendation quiz. Using Gadget's Connections feature, we can connect our app to a Shopify store and pull product data right from the shop.

### What Shopify gives us

The [Shopify connection](https://docs.gadget.dev/guides/connections/shopify#what-does-the-shopify-connection-provide) provides us with access to any of the models surfaced in Shopify's Admin API, as well as an authenticated client and webhook consumption. This connection also allows us to sync data between Shopify and Gadget, both scheduled and on-demand.

### Scopes and Models

To use the Shopify connection, navigate to the Connections view in Gadget via the left-hand navigation. Then, at the top right of the Connections view, select “Add Connection.”


![Add a connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/um1o8idvxvpwvqr2bs3k.jpeg)

Gadget allows you to select only the models you need from Shopify for your application. Each of the scopes listed can grant you access to read or write to many related resources or models. When Gadget receives webhooks relating to your selected resources, it converts the incoming payload into records and maps them to the corresponding model in Gadget. For our app, we're going to choose the Products scope with write permissions, and within the scope, we need the Product, Product Image, and Product Variant models. You'll note that selecting the write permissions will give us read as well, automatically.


![Selecting scopes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fg0oxkb7jg0s5fxxy33m.jpeg)

Now that we have our scope and models selected, we can scroll to the bottom of the Shopify Resources modal to get the connection set up between Gadget and Shopify.


![Setting up the connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hqw60fi1kqhdm6lji7f.jpeg)

Now, we can go over to the [Shopify Partner Dashboard](http://partners.shopify.com/organizations) and create a new custom app:


![Create a new custom app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e35ptkolkwc1ro9s7235.jpeg)

Shopify prompts us for our app's name, URL, and redirection URL. Gadget provides URLs for you, as seen at the bottom of the Shopify Resources modal. Copy those values from Gadget to Shopify, and select “Create app” to save your changes and generate your API keys.


![Adding your Gadget URLs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jufdqyzumh0l37pa8co.jpeg)

Once your app is created, Shopify generates the API key and API secret key that Gadget needs to complete the connection. Copy these values back over to Gadget, and then you can select “Add app” to complete the connection.


![Shopify produces keys for us](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cphhh7fwvq18prr3t1x.jpeg)


![Adding the Shopify keys in Gadget](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dr5gpd1mnbgc6sf6s287.jpeg)

The last step to connecting Gadget and Shopify for our app is to install our app on the shop we wish to sync product data from. In the Shopify Partner Dashboard, click “Select store” under “Test your app” and choose the applicable Shopify store. Follow the prompts, and you should arrive at this screen; you're now connected.


![Success!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08dnwes4gyj1gzc35gom.jpeg)

Now, we can trigger a manual sync between our connected Shopify store and Gadget by selecting “Sync” on the listed connected store.


![Syncing our connected store's data to Gadget](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zy7oi2xe63mstkd77fg.jpeg)

You'll notice now on the left-hand side, under Models, Gadget lists all of the Shopify models you've selected. These models are perfect copies of the corresponding types and associations in Shopify. Each model comes with a CRUD API (create, read, update, delete/destroy) automatically triggered by incoming Shopify webhooks or by running syncs. These CRUD actions can also be triggered by interacting with the API, giving you control over these records right in Gadget. Additionally, if you've selected _any_ Shopify resources, you will also have a Shopify Sync model and a Shopify Shop model in your list of models. Gadget automatically creates these last two models when you configure the Shopify connection, representing the data syncs between Shopify and Gadget and the shop the app is installed on. You can check out the [Shopify connection documentation](https://docs.gadget.dev/guides/connections/shopify#modeling) for more information on these models.

Now that we've established our connection between Shopify and Gadget and we've synced our data, we can build our models for our app.

## Building our Quiz models

### Models outline

We need to create models for our app to represent the components of our Quiz; Questions, Answers, Results, Responses, and the Quiz itself. We need to connect these components by their relationships; Gadget's built-in relationship fields make this connection effortless. Let's start with the Quiz model.

### Quiz

The Quiz model is the backbone of our application. In our concept, our app can have many instances of Quiz, each representing a unique product recommendation quiz created through the app's interface. Our Quiz model needs a couple of properties or fields to get started: a title, maybe a description or body content, and some identifying information like an ID.

Creating a new model in Gadget will take care of some of these fields for us automatically. Each model in Gadget comes with four fields: `ID`, `State`, `Created At`, and `Updated At`.

If we click the + in the Models section of the side nav, we can start our Quiz model:


![Our new Quiz model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cd1oexiafcretl0eilcj.jpeg)

Up at the top of this schema view, we've named the model Quiz, and Gadget has created the API Identifier corresponding to the model's name. From here, we can add our first field, Title. Title is a string, and we cannot create an instance of Quiz without it. So, let's select “Add Field” and create our Title field:


![Adding the title field](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qn2r80w9q3bw2ddojy6r.jpeg)

Again, naming the field will automatically generate the API Identifier. We can then select the type of data we're storing in this field, whether or not it has a default value, and any validations we may want to run against this field on object creation. In the case of Title, we want to select the required validation. We can also add a string length range validation to give Title a minimum and maximum length and a uniqueness validation if we want to ensure no two Quizzes have the same title. Let's add a uniqueness validation.


![Adding the uniqueness validation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xx5dwggdeiickduyfyx.jpeg)

You may have noticed that adding a uniqueness validation triggered an action by Gadget to scan through any existing Quiz records for Title field data to ensure the constraints are met. This is because you can add new fields to models at any point, not just during creation; this allows you to grow and extend your models with your business needs as your app evolves. Gadget will then take care of any migrations or underlying schema changes for you behind the scenes.

Let's now add another field to represent the optional body/description text for the Quiz model:


![Adding the Body field to the Quiz model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgbbgs0nstfduc2gwwx2.jpeg)

For simplicity's sake, we'll set the type to String with no validations.

But what is happening as we create these models and add these fields? Behind the scenes, Gadget automatically generates a CRUD API for each created model and updates this API with any new fields you add, modify, or remove. This means you can quickly test and consume your API immediately after changing your models. Gadget also creates API documentation for your API and a type-safe JavaScript client for you to consume, all in the background as you work.

With that, our Quiz model is done for now, and we can move on to Question.

### Question

Let's create another new model, and call it Question. This model will represent a single Question in a given Quiz. We need just a few fields to get this model going for now: a title and a body, just like Quiz; we also will add three new fields: a sequence, an image URL, and a required field.

To start, let's add Title and Body to Question. Like Quiz, Title is a required string field, though the uniqueness constraint is unnecessary. Likewise, Body is a string field with no validations. Once added, let's move to Sequence.

The Sequence field allows us to declare where this Question will appear in the series of Questions. The Sequence field is technically optional; you could simply sort Questions based on the order they are created, alphabetically, or on another field. However, we've chosen to add a Sequence field to give you more control.

The Sequence field is going to be a Number field. When you set a field to the Number type, you can declare the number of decimals you anticipate the values stored in this field to contain. As we're just working with integers, we'll leave this field as-is. We're going to declare the default value of this field as 1 to guard against null values in the unlikely case that Sequence may not get set. Finally, we're going to add the Required validation to prevent us from creating instances of Question without a Sequence value.


![Sequence](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lrwxp4be6gne3h4dvls.jpeg)

The next field we'll add is Required?, which is a Boolean field that lets us indicate if responding to the given Question is required or not.

![Required? boolean](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nbwvnrfhq27gdq3by9h5.jpeg)

Finally, we'll add the Image URL field. This field uses the URL type, which comes with a special URL validation that parses the input and ensures it is in a valid URL format.

As this field will be optional, that's the only validation we'll need.


![Image URL field](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovr8uzulhmq9p0m8drjw.jpeg)

Now that Question is set, we're going to need some Answers. On to the next model!

### Answer

By now, you should be getting a feel for how the Gadget schema editor works and how quickly you can build expressive models with exactly the fields and logic you need. Next on our list, our Answer model needs just two type-based fields: a Text field and a Sequence field. Our Text field will be a String type field with the Required validation, as our Answer needs to have a text body for users to identify which Answer to choose. Our Sequence field is identical to how we configured it for the Question model; a Number field with no decimals, a default value of 1, and the Required validation. Take a moment to add those two fields to our Answer model, and we can move right along to the Result model.

### Result

Our Quiz now has a Question model and an Answer model, which means we can now create the Result model to represent the outcome of a given set of Answers for a Quiz. The Result model is also how we'll connect outcomes to product recommendations once we make our relationship connections. Result has just two type-based fields: a required Body string-type field to represent the outcome, and an optional Image URL URL-type field with the URL validation, if you wish to provide an image as part of the Result.


![Result fields](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7s5a69ye63bbx3lbkd7.jpeg)

### Response

Our final model for our Quiz app is the Response model. As discussed at the beginning of this tutorial, the Response model represents an instance of taking the Quiz and allows us to track the progress of any given user who has begun taking the Quiz. It will also be a wrapper model that lets us serve a Result to a user by storing the Answers a user has selected and calculating the appropriate Result.

We're going to add two fields to this model: an Email field to log emails for marketing purposes and a Conversion State field, which will hold what stage of the Quiz the given Response has progressed to.


![Conversion state](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnr3ea8xpl6f10htaa55.jpeg)

As in the above screenshot, our Conversion State field is a String-type field, and we're going to give the field a default value of “New” and make this field required. This way, we have the state for each Response from the start through to the finish.

The Email field type, just like the URL field type, has a built-in validation to ensure the value supplied to this field is in the correct format. Therefore, we'll leave this field as optional.

In the last few screenshots, you'll have noticed that we have other fields on our models that we haven't talked about yet that reference other models in our app. Thinking back to our app's relationship diagram, we know we need to link our models together to represent the conceptual connections they share. This brings us to our next step:

### Bringing it all together: Relationships

Now that our models are all established, we can connect them using Relationship fields.

First, let's navigate back to the Quiz model in the schema editor. Then, let's add a Questions field to represent the connection of instances of the Question model to an instance of Quiz:

![Relationship types](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iblwxc01rzt3bvn4sdv9.jpeg)

Adding a Relationship field is much like adding a Type-based field. Near the bottom of the selection list for the field type, we see Relationships listed. These Relationships and their definitions are similar to the Active Record concept of Associations. If you want to dive deeper into how Relationships work in Gadget, you can read our [Relationship and Relationship Fields documentation.](https://docs.gadget.dev/guides/building-models#relationships-and-relationship-fields) For now, we can move forward with the understanding that we can declare a relationship, and Gadget takes care of linking the models together for us without us needing to create and manage foreign keys.

In the case of Questions, we know already that one Quiz **has many** Questions. So, we can model this relationship using the “Quiz **has many** Children” Relationship field. Selecting this relationship type allows us to then select what model is the child model:


![Quiz has many Question](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxvzrl1m4exihk6j6fdn.jpeg)

Once we select Question as the child of Quiz, the schema editor allows us to model what the inverse of the relationship looks like, giving us finer control of the API identifier for this relationship in the generated schema. We'll just refer to the inverse of the relationship as Quiz, so the relationship is then Quiz **has many** Questions, and Question **belongs to** Quiz.


![Question belongs to Quiz](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nde2jkbzwkbv2u576k7g.jpeg)

The other two relationships to model on Quiz are Result and Response. Exactly like Question, a Quiz **has many** Result objects through a Results field, and a Quiz **has many **Response through a Responses field. You can call the inverse field for both of these relationships Quiz.

If we move over to the Question model now, we'll see that Gadget has created a Quiz field on Question for us, linking a Question to one Quiz. In addition to being a child of Quiz, Question is a parent model to the Answer model. A Question can have one-to-many Answers, so we can add an Answers field to our Question model that represents this relationship. Go ahead and add this field now:

![Question has many Answers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nd6gofmmlru812dz5ojb.jpeg)

Answers, as a model, is a child of multiple models. We'll model these relationships through the parent models, so we can leave Answers as-is and proceed on to Result.

Result is another model that is both a child and a parent in our relationship mapping. We'll model the parent side of these relationships:

![Result relationships](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wej4bej9ojvjkog6gy99.jpeg)

A Result **has many** Answer objects, as described by an Answers field, and **has many** Response objects through Responses. This second relationship may seem strange; if we know that Response is an object that wraps and returns Result, why is Result the parent? This allows us to model that a given Result can be linked to many Responses, as every completed instance of Response does return a Result. Otherwise, we'd have to generate a unique Result record for every Response record.

The other relationship to highlight here is a field called Product Suggestion. This field represents the link between a Result and the Shopify Product Variant we're recommending based on the Answers in a given Response. We can declare this relationship from the child side.

First, we select the **belongs to** Relationship type and find Shopify Product Variant in the Parent selection:

![Result belongs to Product Variant](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwm0nxridk2kssddz3r3.jpeg)

![Product Variant has many Results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vx3vhn047mf2nl41xvu7.jpeg)

Once selected, Gadget requires us to create the inverse relationship field on the Shopify Product Variant model. For our app, we're going to pick **has many** Result via a Results field, and that will complete the connection.

Interestingly, this means we've now extended the Shopify Product Variant model beyond what Shopify provides. These additional fields on this connected model are only visible on the Gadget side of the connection and do not sync back to Shopify. Instead, these fields allow us to decorate connection-based models with whatever additional information or logic we may need for our apps, such as relationships. For more on how you can extend Shopify-provided models with Gadget, check out our guide on the [Shopify connection](https://docs.gadget.dev/guides/connections/shopify#what-does-the-shopify-connection-provide).

Finally, let's look at the Response model's relationships. We already have two established for us, as Response belongs both to a Quiz and a Result. We can add one more relationship here to complete our relationship mapping: Response **has many** Answer records via Answers.

![Response has many Answer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zb8qdhwxf4hsavrr5sry.jpeg)

With our models all connected, the schema of our app is complete. We have all the fields and relationships needed to build out our app's UI, which we will do in a minute. First, however, is one last puzzle piece: how does a Response get a Result? To answer this, we're going to need to look at the behaviour of the Response model and employ the use of a Code Effect.

## Code Effects: Calculating the Results

We discussed earlier that Gadget creates a CRUD API for you as you generate and decorate your models. While this is useful, sometimes you need more than just CRUD to build your app. Gadget allows you to extend the CRUD actions with logic through code effects, enabling these actions to unlock more functionality for your app as needed.

Looking at the sidebar menu, we'll see that our currently selected model for the schema editor has two icons: a head with gears and a server stack. The head with gears is our Behavior icon, and the server stack is our Data icon, linking to the data viewer. Let's select the Behavior icon and open the Behavior editor:

![Behavior icon on Response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bm0ax6z9ammlq18srs1.jpeg)

The Behavior editor has two panes: the State Machine on the left and the Actions and States menu on the right. Together, these allow us to add extra logic to standard CRUD actions or add new states and API actions to the model's interface.

![State machine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcygce2ncnmejp8fbycy.jpeg)

For our app, what we're concerned with behavior-wise is the Update action. In our app, the Response record will update through a few user actions: starting the quiz, submitting a response to a quiz, and receiving a result. We can use the Conversion State field on the Response model to represent these states that the Response has arrived at by listening on the Update action for a specific value in that field and then execute some logic to attach a Result record to the Response record. However, we only want to do this if we successfully commit this Response record to Gadget, which we can do through the Success Effect.

Let's open up the Update action and add a Run Code Snippet effect on Success, and name it `calculateResult.js`:

![Success effect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s1o6raos2nq0n9jblpj.jpeg)

A new page icon will appear: click that, and we'll be redirected to the code editor to build our effect.

Our code snippet will look like the following:

```
/**
* Effect code for Update on Response
* @typedef { import("gadget-server").UpdateResponseActionContext } UpdateResponseActionContext
* @param {UpdateResponseActionContext} context - Everything for running this effect, like the api client, current record, params, etc
*/
module.exports = async ({ api, record, params, logger }) => {
  if (record.conversionState == "quiz completed"){
    const potentialResults = await api.answer.findMany({
      filter: {
        response: { isSet: true },
      },
      select: {
        id: true,
        result: {
          id: true,
        },
        response: {
          id: true,
        }
      }
    })
      
    const filteredResults = []
    potentialResults.forEach((p) => {
      if (p.response && (parseInt(p.response.id) === parseInt(record.id)) && p.result) {
        filteredResults.push(parseInt(p.result.id));
      }
    });
      
    // In the case where the mode of filteredResults is bi-modal
    // or multi-modal, select the first result as our successful result 
    // (arbitrary selection)
    const result = mode(filteredResults)[0]
    if (result) {
      const updatedRecord = await api.response.update(record.id, {
        response: {
          result: {
            _link: result.toString(),
          },
          conversionState: "result mapped",
        }
      })
      return updatedRecord;
    }
  }

  return true;
};

function mode(numbers) {
    // as result can be bimodal or multi-modal,
    // the returned result is provided as an array
    // mode of [3, 5, 4, 4, 1, 1, 2, 3] = [1, 3, 4]

    const modes = [];
    const count = [];
    let i;
    let number;
    let maxIndex = 0;
 
    for (i = 0; i < numbers.length; i += 1) {
        number = numbers[i];
        count[number] = (count[number] || 0) + 1;
        if (count[number] > maxIndex) {
            maxIndex = count[number];
        }
    }
 
    for (i in count)
        if (count.hasOwnProperty(i)) {
            if (count[i] === maxIndex) {
                modes.push(Number(i));
            }
        }
 
    return modes;
}
```

Copy and paste the above code into your `calculateResult.js`, and let's walk through this snippet at a high level:

- We check that the updated record has a specific conversion state of “quiz completed.”
  - This is one of the conversion states we'll specify through the API and represents a response state where the user has selected their answers and submitted their response for a result.
- Then, we find the applicable Answers for the given Response, and:
  - Find the most common Result ID between the Answers to declare as the Response Result.
  - We then link this Result to the Response record.
  - Then, we update the conversion state on the Response record to reflect the mapping of the Result to the Response.
  - Finally, return the updated Response record.

The mode function below our exported module is the math we use to calculate the most common Result in the list of potential Results.

With our snippet in place, our models created and relationships connected, we're ready to consume our app's API and build our front end!

## Building the UI

### Consuming the Gadget Client with Next.js

Part of what makes Gadget so powerful is how it automatically generates API client packages for you in both JavaScript and TypeScript, making the job of consuming and interacting with your app's backend nearly effortless. We're going to consume our API in two ways for our app: a freestanding app hosted on Vercel with both admin- and customer-facing views (headless) and a customer-facing UI embedded in our Shopify shop's theme.

### Headless Build

#### Getting started with the UI

We will build our freestanding app using React and Next.js and use the Polaris library for our components. You can copy the following app into an empty Github repo to get you started. This app provides both the admin-facing and customer-facing UIs; you'll just need to take a few steps to get up and running.

[Product Recommendation Quiz App UI](https://github.com/gadget-inc/examples/tree/main/packages/product-recommendations-quiz-app/product-quiz-ui)

Once you've copied the app into your own empty Github repo, you'll need to update the following:

1. In the package.json, remove the `@gadget-client/alida-quiz-app-2": "^1.164.0"` dependency
2. Locally in your app's `product-quiz-ui` folder, install React, Gadget's React bindings NPM package `npm install @gadgetinc/react react` and your [client's NPM package](https://docs.gadget.dev/api/blog/installing#node-module) and ensure it is now in the package.json as a dependency.
3. In the `.env` file, you'll need to replace [YOUR API KEY] with your app's API key for writing to production, which you can find in Gadget under Settings > API Keys
4. In `api.js`, you'll need to update the client import declaration to reference your client package; `import { Client } from "@gadget-client/[YOUR CLIENT HERE]";` on line 1
5. Ensure your `.env` file is added to the project's `.gitignore.`

Once that's complete, you may want to run a quick `npx next` in your terminal to boot your app locally and ensure you've replaced all values as expected. Then, when the app is running locally at [http://localhost:3000](http://localhost:3000), we can test our app and make our first quiz!

#### Making our first Quiz

Now for the fun part, making a quiz! Take a moment and make a quiz with your app; you can use our [demo quiz](https://product-recommendation-quiz-ui-whateverbee.vercel.app/quiz/view/157) as inspiration or create your own!

Once your quiz is complete with questions, answers, and results, go ahead and take your quiz.

Now, we can look at records in Gadget and see how our front-end app connects with Gadget through the client and makes API calls against it. If we look at the Quiz data by selecting the Data icon on the Quiz model in the left-hand sidebar, we should see at least one instance of Quiz, including its ID, title, and body. We can also inspect our other records to see how our pieces work together to create our quiz experience.

When you've got a quiz that you're happy with, note the ID of the quiz, if you're planning on building the quiz right into your Shopify store. Otherwise, let's deploy our app to Vercel.

#### Deploying on Vercel

If you've never worked with it before, Vercel is a front-end deployment and hosting platform and is particularly useful for Next.js projects like ours. To begin, let's head to [https://vercel.com/new](https://vercel.com/new) and log in with our Github account. Once you've authorized Vercel for your account, you should be able to see your app repo as an available option in Vercel.


![Vercel home](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4id99ph8ie239dmreoqc.jpeg)

Select your repo, and you'll be able to configure your environment for your first deployment:

![Vercel new app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1w3ba6n30zhamp1upbwe.jpeg)

For your Framework Preset, select Next.js. Next, ensure that the chosen Root Directory is the root of your app's directory, and then select Environment Variables. Finally, you'll add your API key (the same one in your .env file), so your app can authenticate your client at runtime.

![Vercel env keys](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zsxgri7n2qh0nwj53749.jpeg)

Once you've added your API key, hit Deploy, and in a moment, your app should be deployed on Vercel. For more on Vercel, check out their excellent [Get Started](https://vercel.com/docs/get-started) guide.

### Shopify Build

#### Installing in the Shopify theme

While we used an NPM package to install our client into our freestanding app, we'll need another method of calling the client in our Shopify shop's theme. Gadget allows us to call our API client directly with a script tag.

We only need the client to run to serve the desired product recommendation quiz. In this case, we'll make a new template for the Page resource and then use it on a page we'll create to hold the quiz.

In your Shopify admin for your shop, head to Online Store > Themes and select Edit Code under the Actions menu for the theme you wish to edit.


![Shopify theme editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wggci6lhf3tanw5tt2pm.jpeg)

Under Templates, select “Add a new template” and add a template called `page.quiz.json.`

Replace the generated file with the following JSON:

```JSON
{
  "sections": {
    "main": {
      "type": "quiz-page",
      "settings": {
      }
    }
  },
  "order": [
    "main"
  ]
}
```

Next, under Sections, create a new section called _quiz-page.liquid_. This will be the content that the _page.quiz.json_ file returns.

We're going to replace this page with the following code:

```
<link rel="stylesheet" href="{{ 'section-main-page.css' | asset_url }}" media="print" onload="this.media='all'">
<link rel="stylesheet" href="{{ 'component-rte.css' | asset_url }}" media="print" onload="this.media='all'">

<script src="YOUR DIRECT SCRIPT TAG URL HERE"></script>
<script>
  window.GadgetClient = new Gadget({ authenticationMode: { apiKey: "YOUR API KEY" } })
</script>
<script src="{{ 'product-quiz.js' | asset_url }}" defer="defer"></script>
<noscript>{{ 'section-main-page.css' | asset_url | stylesheet_tag }}</noscript>
<noscript>{{ 'component-rte.css' | asset_url | stylesheet_tag }}</noscript>

<div class="page-width page-width--narrow">
  <h1 class="main-page-title page-title h0">
    {{ page.title | escape }}
  </h1>
  <div class="rte">
    {{ page.content }}
  </div>
  <div>
    <product-quiz class="quiz">
      <form action="post" class="form" novalidate="validate">
        <h2 class="product-quiz__title">Loading...</h2>
        <div class="product-quiz__body">
          <span>
            
          </span>
        </div>
        <div class="product-quiz__questions" id="questions">
          <div class="product-quiz__question">
            <span class="product-quiz__question-answer">
            </span>
          </div>
        </div>
        <button
                type="submit"
                class="product-quiz__submit button button--secondary"
                >
          Get my results!
        </button>
      </form>
    </product-quiz>
  </div>
</div>

{% schema %}
{
"name": "t:sections.quiz-page.name",
"tag": "section",
"class": "spaced-section"
}
{% endschema %}
```

We just need to replace the "YOUR DIRECT SCRIPT TAG URL HERE" with your script tag, and "YOUR API KEY" with your API key, and we're ready for the last step: using our client to return a selected quiz.

#### Using our client with JavaScript

Under the Assets section in the sidebar, select **Add a new asset** and create a new JavaScript file called _product-quiz.js_. You can then add the following to that file:

```
async function updateAnswers(answers, response) {
 const updatedAnswers = await answers.forEach((answer) => {
      		 GadgetClient.mutate(`
              mutation($id: GadgetID!, $answer: UpdateAnswerInput) {
                updateAnswer(id: $id, answer: $answer) {
                  success
                  answer {
                    id
                    response {
                      id
                      state
                      conversionState
                      createdAt
                      email
                      result {
                        id
                        state
                        body
                        createdAt
                        imageUrl
                        productSuggestion {
                          id
                          price
                          title
                        }
                        quiz {
                          id
                          state
                          body
                          createdAt
                          title
                          updatedAt
                        }
                        updatedAt
                      }
                    }
                    sequence
                    text
                  }
                }
			}`, { 
               "id": answer, 
               "answer": { 
                 "response": {
                   "_link": response.id 
                 } 
               } 
             }
            );
          }
       );

	return updatedAnswers;
}

async function createResponse(quiz) {

const response = await GadgetClient.mutate(`
  mutation ( $response: CreateResponseInput) { createResponse(response: $response) {
      success
      errors {
        message
        ... on InvalidRecordError {
          validationErrors {
            apiIdentifier
            message
          }
        }
      }
      response {
        __typename
        id
        state
        answers {
          edges {
            node {
              id
              state
              createdAt
              question {
                id
                state
                body
                createdAt
                imageUrl
                required
                sequence
                title
                updatedAt
              }
            }
          }
        }
        conversionState
        createdAt
        email
        quiz {
          id
          state
          body
          createdAt
          title
          updatedAt
        }
        updatedAt
      }
    }
  }
`, { "response": { "quiz": { "_link": quiz.id }, "conversionState": "in progress", } })
	return response;
}

async function updateResponse(response) {
const updatedResponse = await GadgetClient.mutate(`mutation ($id: GadgetID!, $response: UpdateResponseInput) {
  updateResponse(id: $id, response: $response) {
    success
    errors {
      message
      ... on InvalidRecordError {
        validationErrors {
          apiIdentifier
          message
        }
      }
    }
    response {
      __typename
      id
      state
   
      conversionState
      createdAt
      email
      quiz {
        id
        state
        body
        createdAt
        title
        updatedAt
      }
      result {
        id
        state
        body
        createdAt
        imageUrl
        productSuggestion {
          id
          price
          title
			product {
              title
              handle
			  body
              images {
              edges {
                  node {
                      source
                      }
                    }
                  }
                }
              }
        quiz {
          id
          state
          body
          createdAt
          title
          updatedAt
        }
        updatedAt
      }
      updatedAt
    }
  }
}
`, { "id": response.id, "response": { "conversionState": "quiz completed" } })
  return updatedResponse;
}

async function fetchQuiz() {

const quiz = await GadgetClient.query(`query getOneQuiz {
quiz (id: [YOUR QUIZ ID]) {
	id,
	title,
	body,
	questions {
  		edges {
  		node {
    		id,
			title,
			body,
			imageUrl,
			required,
			sequence,
			answers {
				edges {
					node {
						id,
						text,
						sequence,
						question {
							id,
							},
						},
					},
				},
    		},
  		},
	},
	results {
      edges {
        node {
          id,
          state,
          body,
          imageUrl,
          productSuggestion {
            			id,
            			price,
            			title,
						product {
						title,
						handle,
						},
          			},
				},
			},
		},
	},
}`)


 return quiz;
}

let selectedAnswers = []
function selectAnswer(answer) {
  selectedAnswers.push(answer);
  let elId = event.srcElement.id;
  let parent = document.getElementById(elId).parentNode;
  parent.innerHTML = "<h3>Answer selected</h3>";	
}

fetchQuiz().then(function(quiz) { 

const quizData = quiz.quiz;
const questions = quizData.questions.edges;

  if (!customElements.get('product-quiz')) {
    customElements.define('product-quiz', class ProductQuiz extends HTMLElement {
      constructor() {
        super();
		
        this.form = this.querySelector('form');
		this.heading = this.querySelector('form h2');
		this.heading.innerHTML = quizData.title;
		this.body = this.querySelector('.product-quiz__body span');
		this.body.innerHTML = quizData.body;
		this.questions = this.querySelector('.product-quiz__questions');
        const questionContainer = this.querySelector('.product-quiz__question');
		const answerContainer = this.querySelector('.product-quiz__question-answer');
		
      	let renderedQuestions =	questions.sort((a, b) => a.node.sequence - b.node.sequence).forEach((question, i) => {
			let clonedDiv = questionContainer.cloneNode(true);
			clonedDiv.id = 'question_' + i;
			clonedDiv.insertAdjacentHTML('beforeend', '<div><h3>' + question.node.title + '</h3><br/></div>');
			this.questions.appendChild(clonedDiv);
			let answers = question.node.answers.edges;
          answers.sort((a, b) => b.node.sequence - a.node.sequence).forEach((answer, j) => {
            let clonedSpan = answerContainer.cloneNode(true);
			clonedSpan.id = 'answer_' + i + '_' + j;
			clonedSpan.insertAdjacentHTML('beforeend', '<span><a class="button answer" id="' + clonedSpan.id + '" onClick=(selectAnswer(' + answer.node.id + '))>' + answer.node.text + '</a><br/></span><br/> ');
			clonedDiv.appendChild(clonedSpan);
          })
		});
		
	
        this.form.addEventListener('submit', this.onSubmitHandler.bind(this));
		
      }

      onSubmitHandler(evt) {
        evt.preventDefault();

        const submitButton = this.querySelector('.product-quiz__submit');

        submitButton.setAttribute('disabled', true);
        submitButton.classList.add('loading');
		
        createResponse(quiz).then(function(response) {
			const currentResponse = response.createResponse.response

          updateAnswers(selectedAnswers, currentResponse).then(function(results) {
            updateResponse(currentResponse).then(function(updatedResponse) {
				const finalResponse = updatedResponse.updateResponse.response;
				
              if (finalResponse) {
				const result = finalResponse.result;
				console.log(finalResponse);

                if (result) {
				  const imgUrl = result.productSuggestion.product.images.edges[0].node.source
				  const productLink = result.productSuggestion.product.handle
                  const resultHTML = `<div><h3>` + result.body + " - " + result.productSuggestion.product.title + `</h3><br/><p><img src=` + imgUrl + ` width="50%" height="50%"/><br/> <p>` + result.productSuggestion.product.body + `</p></br><a class="button" href="/products/` + productLink + `">Check it out!</a></div>`
                  document.getElementById("questions").innerHTML = resultHTML;
                  submitButton.classList.remove('loading');
				  submitButton.classList.add('hidden');
                  }
              	}
              }
	    )
          })
        })
      }
    });
  }
});
```

You'll need to make one adjustment here: in the quiz query, you just need to replace (id: [YOUR QUIZ ID]) with the ID of the quiz you want to return. Save your changes, and we're ready to go! Head over to the Pages section of the Shopify admin, and create a new page for your quiz. You can add whatever title and body content you may want for the page and then set the template to use your new quiz template.

![Shopify page editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oguqyxwod86ce6yw6fnc.jpeg)

Once you save this page, you're all done! View the page to see your quiz right in your Shopify store, ready to recommend products to your shoppers.

![Completed quiz in Shopify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y97cx02kxozs0v5kh70h.jpeg)

## Conclusion

Today, you've learned how Gadget and Shopify can work together to create engaging buying experiences for your shoppers while providing an approachable platform to build your app in a fraction of the time it takes to do so from scratch. Feel free to expand on this app; since we have the Product Variant ID of the recommended product, we can construct a cart for the shopper on the front-end using Javascript, enabling a faster buying experience. Additionally, you could use Gadget's built-in authentication to add a login layer to the admin UI, add editing functionality to the quiz builder, and more!

Want to know more about building effortless, expressive apps with Gadget? Check out their [Guides](https://docs.gadget.dev/guides) and get building today!

Need support? Join Gadget's [Discord](https://discord.gg/tY4ZjWdMcB), or [book office hours](https://calendly.com/gadget-alida/lets-chat) with Gadget's Developer Advocate team!