When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react';
import Link from 'next/link';

import { urlFor } from '../lib/clients';

const Product = ({ product: { image, name, slug, price } }) => {
  return (
    <div>
      <Link href={`/product/${slug.current}`}>
        <div className="product-card">
          <img 
            src={urlFor(image && image[0])}
            width={250}
            height={250}
            className="product-image"
          />
          <p className="product-name">{name}</p>
          <p className="product-price">${price}</p>
        </div>
      </Link>
    </div>
  )
}

export default Product

the code mentioned above

Answer №1

It seems like the value of slug is changing after the Product component has been rendered. To address this issue, you may consider not displaying anything until the value of slug is correct, which can be accomplished using a React effect hook.

import React, { useEffect } from 'react';
import Link from 'next/link';

import { urlFor } from '../lib/clients';

const Product = ({ product: { image, name, slug, price } }) => {

  useEffect(() => {
    // Logging the value of `slug` as it changes
    console.log('value of slug:', slug);
  }, [slug]);

  // Rendering nothing if `slug` is undefined
  if (!slug) return null;

  return (
    <div>
      <Link href={`/product/${slug.current}`}>
        <div className="product-card">
          <img 
            src={urlFor(image && image[0])}
            width={250}
            height={250}
            className="product-image"
          />
          <p className="product-name">{name}</p>
          <p className="product-price">${price}</p>
        </div>
      </Link>
    </div>
  )
}

export default Product

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

Angular Notification not visible

I have been attempting to display a notification after clicking a button using the angular-notifier library (version: 4.1.1). To accomplish this, I found guidance on a website called this. Despite following the instructions, the notification fails to app ...

JavaScript Filter Function: filtering based on multiple conditions (either one can evaluate to true)

I seem to be missing something very simple here. I am working with an array of objects that contains various information. Depending on user interaction, I want to filter out certain objects; let arr = [ {'num': 1, 'name': 'joe&a ...

Develop a time-sensitive store system using HTML and JavaScript that toggles between open and closed status based on set

I am looking to develop a time-based Open/Closed store using HTML and JavaScript. The concept is that on Fridays, the element with id="friday" should be displayed, otherwise, show the element with id="week". Additionally, if the time i ...

When navigating through a view in backbone.js, ensure to include an argument in the routing process

Looking to include an argument while routing within a Backbone.js application Below is the script: var AppRouter = Backbone.Router.extend({ routes: { 'toolSettings/(:action)' : 'toolSettings' } }); var initialize = function ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

Don't delay in fulfilling and resolving a promise as soon as possible

Currently, I am facing an issue with a downstream API call that is returning a Promise object instead of resolving it immediately. This is how I am making the downstream call: const response = testClient.getSession(sessionId); When I console.log(response ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

What's the best way to mount a file on a field?

Can you assist in resolving this issue by utilizing a form on JSFiddle? If a user fills out the following fields: name, email, phone, message The data should be output to the console. However, if a user adds a file to the field attachment No output ...

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

What role does a promise play in rendering code asynchronous?

While we often use promises to avoid the dreaded function callback hell, a question remains: where exactly in the event loop does the promise code execute and is it truly asynchronous? Does the mere fact that the code is within a promise make it asynchron ...

Retrieving information from a datatable in vb.net with an array

Working on a chart using highcharts with code behind in vb.net... I have a datatable structured like this: Date - speed - data 2011 10k 6 2011 18k 7 2012 20k 10 2012 10k 2 2013 14k 4 2013 20k 6 Previously, to ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

What are the steps for accessing a server-side WebControl from the client side?

Issue Overview: I am facing a problem with managing different types of input values in my dialog box. Depending on the selection from a dropdown list, the required input could be simple text, a date, or specific data from a database. I have successfully i ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

Enhance TypeScript in WebStorm: Update or Upgrade the bundled version

What is the best way to update or upgrade the default version? https://i.sstatic.net/hQFUd.png Important note: I prefer not to manually modify and switch to a custom version like: https://i.sstatic.net/wejP7.png ...

Shuffling decks of cards among players at a table using JavaScript

Seems like such a simple task, but I can't seem to get it right. The idea is to have an array of 8 other arrays, each containing sets of cards (although in this case, they just have random numbers). Depending on whether passDirection is set to -1 or 1 ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

standards for matching patterns (such as .gitignore)

Throughout my experience, I have utilized various tools designed to search a codebase for specific files and then carry out operations on those files. One example is test libraries that identify all the necessary files for execution. Another common tool is ...