How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered:

Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'

Is there a way to resolve this error without using implicit typing?

import { useRouter } from 'next/router'
import { useBlogQuery } from '@graphql/generated'

const router = useRouter()
const blogId = router.query.blogId

const BlogQuery = useBlogQuery({
    variables: {
        id: blogId
    },
})

Answer №1

This type of error detection can actually be quite helpful.

For instance:

  1. www.example.com router.query.blogId = undefined
  2. www.example.com/?blogId=1&blogId=2 router.query.blogId = [1, 2]
  3. www.example.com/?blogId=1 router.query.blogId = 1

If you are absolutely certain that cases 1 & 2 will never occur, you could handle it like this:

const blogId = router.query.blogId as string;

However, it might be a better practice to implement some logic for when blogId is either undefined or an array.

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

Guide on retrieving and presenting images in React from a Cloudinary URL stored in MongoDB

Recently, I started integrating Cloudinary into my application for uploading images. These images are stored in a MongoDB database as URL links. The upload process was successful, and this is how the database looks after saving: id:5f90315331dc1727bc869afe ...

trouble with react-table's default height and flexible design

I am facing an issue with my React table configuration. I have set up scrollable columns and header following a similar example here: https://codesandbox.io/s/kowzlm5jp7?file=/index.js:281-310 In the table styles, I have specified a height like this: ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

A custom function that changes the state of a nested object using a specified variable as the key argument

My goal is to update the state of an object using a function called updateDatas. This function takes the arguments key, possibly subKey, and value. interface Datas { code: number; item1: Item; } interface Item { id: number; name: string; } const ...

How can I stop MUI Button from automatically becoming fullWidth?

One of the challenges I encountered was styling a Button component from MUI: export const ButtonStyle = styled((props) => <Button {...props} />)(({ theme }) => ({ marginTop: 8, marginBottom: 8, width: 'auto', borderRad ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

React- Struggling to modify state from child component using function declared within a parent component

This is my main component: import React, {useState} from 'react'; import SearchBar from '../components/SearchBar'; import WeatherDisplay from '../components/WeatherDisplay'; import LocationInfo from '../components/Locat ...

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

I attempted to post a collection of strings in ReactJS, only to receive a single string response from the Web

I was troubleshooting an issue where only one string from ReactJS was being sent to WebApi instead of an array of strings. Below is the ReactJS code snippet I used: import React, { useState } from "react"; import axios from "axios"; e ...

Struggling to maintain consistent updates on a child element while using the @Input property

I need to ensure that the data source in loans.component.ts is updated whenever a new loan is submitted from loan-form.component.ts. Therefore, in loan-form.component.ts, I have the following function being called when the form is submitted: onSubmit() { ...

Tips for moving a polygon while dragging a marker within its boundaries

Currently, I have a map displaying polygons and markers, accompanied by a sidebar featuring tool buttons (similar to the setup showcased in this demo: ). Each marker on my map is connected to the respective polygon stored in my database. When I utilize the ...

Develop an event listener in a React Component that watches for changes

I have a React component and I am looking to implement an "onChange" event that can be detected by another component in the application. const FirstComponent = () => { // Implement functionality // How can I create an event here that can be detec ...

What is the process for downloading a package from unpkg or adding an unpkg package to dependencies?

Challenge I attempted to install IPFS from the unpkg website. https://www.unpkg.com/browse/[email protected] / My Project This is a project built with React. Unfortunately, I am having trouble downloading this package or installing it in my packa ...

Exploring the latest MUI Styles in Scoping Version 5

We are currently in the process of transitioning our legacy application to React and MUI. To ensure that there is no styling conflict between the old and new parts of the application, we have implemented scoped styles by combining an id selector with a des ...

Having difficulty animating the height transition of the NextJS Image component

On my webpage, I have a headerbar that changes size (from 120px to 70px) when the user scrolls down. I successfully implemented this transition using Tailwind classes and a height transition. Now, I am trying to make the site logo resize along with the hea ...

The React application's route is not functioning properly following deployment on IIS

Hey there, I'm a beginner in the world of reactjs and currently struggling with deploying my react app on IIS. After running npm run build, a build folder is generated. I then transferred this folder to my IIS server. However, when I try to access th ...

Backend is currently unable to process the request

Whenever a user clicks on a note in my notes page, a request is supposed to be made to the backend to check if the user is the owner of that particular note. However, for some reason, the request is not being processed at all. The frontend is built using ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

How can I ensure that every dependency in my package.json is updated to the newest version using Yarn?

My current react app is using deprecated dependencies and in order to get it functional, I need to update these dependencies to more recent (yet stable) versions. According to a discussion on Stack Overflow, for updating dependencies in package.json to th ...