Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser.

While I successfully retrieve all products using the following code:

export async function getAllProducts() {
  const productData = await client.fetch('*[_type == "product"]');

  return productData;
}

the problem arises when I attempt to retrieve products by slug, as the returned value is null:

export async function getProductBySlug(slug) {
  const currentData = await client.fetch(
    `*[_type == "product" && slug.current == '${slug}'][0]`
  );

  return currentData;
}

I'm scratching my head trying to figure out where I might be going wrong. Any insights?

Answer №1

Enclosing the slug parameter in curly brackets {} within the function name allows for the seamless transfer of dynamic data, eliminating any issues with null values.

export async function getProductBySlug({ slug }) {
  const currentData = await client.fetch(
    `*[_type == "product" && slug.current == '${slug}'][0]`
  );

  return currentData;
}

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

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

What is the quickest method to perform a comprehensive comparison of arrays and combine distinct objects?

I am currently working with NextJS and Zustand and I have a state in Zustand that consists of an array of objects: [{a:1, b:2}, {a:2, b:3}] Additionally, there is another incoming array of objects that contains some of the existing objects as well as new ...

What are some creative ways to reveal a concealed card through animation?

I have a collection of MUI cards where one card remains hidden until the others are expanded. My goal is to add animation to the hidden card so it doesn't abruptly appear. Below is the styling and logic for achieving this: ** Styling ** const useStyl ...

Struggling to establish a stable MQTT connection with Next.js? Many users have encountered errors and faced unstable connections. Read on

Currently, I am developing a real-time web application using next.js 14 along with the App router. In this project, I have integrated an MQTT connection that utilizes Mosquito under the hood. To establish the connection to the broker, I am leveraging the m ...

Tips for eliminating nested switchMaps with early returns

In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve th ...

Is there a way to bypass the "Error: Another application is currently displaying over Chrome" message using Javascript or Typescript?

Can the "Another app is displaying over chrome error" be bypassed using JavaScript or TypeScript? Error Message: https://i.stack.imgur.com/iSEuk.png ...

Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information. let lang = this.$store.state.lang ...

Modifying the order of Vuetify CSS in webpack build process

While developing a web app using Vue (3.1.3) and Vuetify (1.3.8), everything appeared to be working fine initially. However, when I proceeded with the production build, I noticed that Vue was somehow changing the order of CSS. The issue specifically revol ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

Compile a roster of service providers specializing in unit testing imports

Recently joining a new team that works with Angular, they asked me to implement unit testing on an existing project built with Angular 8. After researching the best approach, I decided to use Karma + Jasmine for testing. I set up a .spect.ts file structure ...

Retrieving Progress Updates from a PHP Script Using XMLHttpRequest

I am currently using JavaScript to execute an XMLHttpRequest to a PHP script that returns data. My goal is to display a progress bar for the user instead of a spinning circle, indicating the progress of fetching and receiving the data. While I understand t ...

Unable to install react-dom/test-utils using npm

I recently included two libraries in my package.json "devDependencies": { ... "react-dom/test-utils": "*", "react-test-renderer/shallow": "*" }, These were recommended by the React documentation to align with version 16 of the React ecosy ...

Utilizing Apollo Client cache for Server-Side Rendering

Currently, I am utilizing @apollo/client in combination with Next.js for Server Side Rendering. The data retrieval process is via wp-graphql, making it essential to render on the server side. However, there is a minor setback - the cache persists indefinit ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

How to showcase images and text from an array of objects using React

I'm currently working on a React lightbox that is supposed to display a loop of objects containing images and text. However, I'm facing an issue where the images are not showing up with the corresponding text label as intended. It seems like I a ...

Why React.js and webpack are restricting the use of var, let, const?

I'm facing a puzzling issue that I just can't seem to solve. Let me show you a snippet from my Graph.js file: class Graph extends React.Component { @observable newTodoTitle = ""; s = 40 The error in webpack is showing up like this: E ...

Tips for distinguishing individual submit buttons within a foreach loop

Here is my code snippet: <?php require_once 'core/init.php'; if($result = $db->query ("SELECT * from countries")) { if($count = $result->num_rows) { $rows = $result->fetch_all(MYSQLI_ASSOC); } ...

JS form validation malfunctioning

XHTML <form name="suggestion" method="post" action="suggestion.php" class="elegant-aero" onSubmit="return validate()" > <label> <span>Message :</span> <textarea id="Message" name="m ...