I am encountering a TypeScript error with URLSearchParams. The object cannot be successfully converted to a string using the toString() method

During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams.

index.js

import express from 'express';
import cors from 'cors';
import * as recipeAPI from './recipe-api'


const app = express();

app.use(express.json());
app.use(cors());

app.get("/api/recipe/search", async (req,res) => {
    const searchTerm = req.query.searchTerm as string;
    const page = parseInt(req.query.page as string);
  
    const results = await recipeAPI.searchRecipes(searchTerm, page);
    return res.json(results);
})

app.listen(5000, () => {
    console.log("Server running on localhost 5000")
})

recipe-api-ts

import { error } from "console";
import { URLSearchParams } from "url";

const API_KEY = process.env.API_KEY;

export const searchRecipes = async (searchTerm: string, page: number) => {
    if(!API_KEY){
        throw new Error("API key not found")
    }

const baseURL = "https://api.spoonacular.com/recipes/complexSearch";
const url = new URL(baseURL);

const queryParams = {
    apiKey: API_KEY,
    query: searchTerm,
    number: 10,
    offset: (page - 1) * 10,
  };

  const searchTerms = new URLSearchParams(queryParams);

  url.search = searchTerms.toString();

  try {
    const searchResponse = await fetch(url.toString());
    const resultsJson = await searchResponse.json();
    return resultsJson;
  } catch (error) {
    console.error(error);
  }
};

An error occurs in the recipe-api-ts file at this line

const searchTerms = new URLSearchParams(queryParams);

TSError: ⨯ Unable to compile TypeScript: src/recipe-api.ts:23:43 - error TS2345: Argument of type '{ apiKey: string; query: string; number: number; offset: number; }' is not assignable to parameter of type 'string | URLSearchParams | Record | Iterable<[string, string]> | readonly [string, string][] | undefined'. Type '{ apiKey: string; query: string; number: number; offset: number; }' is not assignable to type 'Record'. Property 'number' is incompatible with index signature. Type 'number' is not assignable to type 'string | readonly string[]'.

23 const searchTerms = new URLSearchParams(queryParams);

This error appears after compilation.

Answer №1

The issue you're experiencing is due to URLSearchParams only accepting string values in the object. Your number and offset values are currently of type number, which is causing this error. To resolve this, convert them to strings.

const searchParams = {
    apiKey: API_KEY,
    query: searchTerm,
    number: `10`,
    offset: `${(page - 1) * 10}`,
  };

const parameters = new URLSearchParams(searchParams);

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

Accessing the outer index in a nested loop using Handlebars

Imagine I have the code below: <div> {{#each questions}} <div id="question_{{@index}}"> {{#each this.answers}} <div id="answer_{{howToGetThisIndex}}_{{@index}}"> {{this}} </div> {{/each}} </div> ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Vue 3 Single Page Application. When selecting, it emits the language and the contentStore does not update the content exclusively on mobile devices

My Vue 3 Single Page Application is built on Vite 4.2 and TypeScript 5.02. When I click to select a language, it emits lang.value and in the parent component App.vue, contentStore should update the content. It works flawlessly on my Linux Ubuntu desktop i ...

Issues with implementing passport local authentication in node.js

I have been attempting to incorporate passport + express + mongodb functionality for local authentication, but I am encountering issues. Despite following examples, including the one on the official page which includes the line app.use(app.router);, I am ...

Troubleshooting the malfunction of images in Node.js located outside the HTML path

Currently, I'm developing a user profile page using nodejs where users can view their avatars after logging in. Users are able to upload files to the uploads folder which is located outside the standard htmlpath. Here's an overview of my folder s ...

Is it necessary to configure modules using app.use in every route in express.js?

I recently learned that it is best practice to include the express module individually in each route file, rather than globally in app.js. Now I'm questioning whether I need to duplicate all the app.use statements in each route file or if I can just ...

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Developing a Data Generic State Management System in Angular using TypeScript

Implementing a Generic StateManagierService that can handle any type, allowing users to receive new state and data upon state change. However, something seems to be missing. export class StateManagierService<T> { private _state$: BehaviorSubject< ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

Is it feasible to customize Angular Material Constants within select.ts?

I am looking for a way to dynamically set the height of a select element by passing a variable, but the height is currently a constant in the material code (select.ts). Check out the mat-select documentation View the source code on Github: material2 / se ...

what is the best method to transfer request and response data between different routes in an express application

My express routes are set up as follows: router.get( "/auth/google/callback", passport.authenticate("google", { failureRedirect: "/error", session: false }), function(req, res) { var token = req.user.token; res.redirect("/getDa ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Experiencing difficulties sending AJAX requests to an Express server while utilizing React Router

I am encountering difficulties with making ajax requests to fetch data from a MongoDB database. The application is coded using React, utilizing React-Router for routing and running on an Express server. The ajax calls are being handled using whatwg-fetch. ...

Creating a Loader while navigating routes in Next 13: A step-by-step guide

During the navigation to Next 13, I want to display a loading indicator on my screen to inform the user about the ongoing navigation process. I attempted to implement this using the traditional method, but I encountered difficulties as I cannot utilize ne ...

Utilize Angular6 and NodeJS to exhibit images stored on a server file system

Successfully uploaded images to a server but struggling to find a tutorial on how to display these images using Angular6 and NodeJS. Any help would be greatly appreciated. Thank you in advance. Edit: After many trials and errors, I was able to retrieve a ...

Troubleshooting connection issues with a Chat app using Socket.io and Express: How to fix ERR

Currently, I'm immersed in a tutorial that delves into creating a rock-paper-scissors game with an integrated chat feature using socket.io and express. My focus is solely on crafting the chat component. However, a frustrating error keeps cropping up w ...

Using webpack to generate sourcemaps for converting Typescript to Babel

Sharing code snippets from ts-loader problems may be more suitable in this context: Is there a way to transfer TypeScript sourcemaps to Babel so that the final sourcemap points to the original file rather than the compiled TypeScript one? Let's take ...

Learn how to efficiently transfer row data or an array object to a component within Angular by utilizing the MatDialog feature

My goal is to create a functionality where clicking on a button within a specific row opens up a matDialog box displaying all the contents of that row. Below is the HTML snippet: <tr *ngFor="let u of users"> <td data-label="ID& ...