Search code examples
typescriptpostgresqlexpressbackendurlsearchparams

URLsearchparams typescript error. I can't convert the object to string using toString()


I am creating a react app with postgres, express, node, typescript. But i encountered a problem while creating backend code. There is a error while using 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);
  }
};

getting error in recipe-api-ts file in 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<string, string | readonly string[]> | Iterable<[string, string]> | readonly [string, string][] | undefined'. Type '{ apiKey: string; query: string; number: number; offset: number; }' is not assignable to type 'Record<string, string | readonly string[]>'. Property 'number' is incompatible with index signature. Type 'number' is not assignable to type 'string | readonly string[]'.

23 const searchTerms = new URLSearchParams(queryParams);

This is error after compile shows.


Solution

  • URLSearchParams only accepts string values in your object number and offset values are of type number which is causing this error convert it to string to fix this error

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