Home > Mobile >  URLSearchParam type {property: value} is not assignable to undefined & Argument Type {property: valu
URLSearchParam type {property: value} is not assignable to undefined & Argument Type {property: valu

Time:08-17

I keep getting this error when I try to execute the following code. Basically it takes in the given refresh token and send a POST request with the URLSearchParams to the URL. But for some reason URLSearch params keeps on throwing an error.

enter image description here

Code

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token,
    }),
  })
  return response.json()
}

where refresh_token is a constant defined by an enviornment variable.

Error

Argument of type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to parameter of type 'string | string[][] | Record<string, string> | URLSearchParams | undefined'.
  Type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to type 'undefined'.ts(2345)

CodePudding user response:

The problem is that refresh_token is potentially undefined and URLSearchParams only supports fields with string values.

There are several options here...

  1. Provide a fallback string value

    new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: refresh_token ?? ""
    })
    
  2. Add parameters optionally

    const body = new URLSearchParams({ grant_type: "refresh_token" });
    if (refresh_token) {
      body.append("refresh_token", refresh_token);
    }
    
  3. If you're sure that refresh_token is not undefined, assert it as so

    new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: refresh_token!
    })
    

CodePudding user response:

To solve this all I did was remove the URLSearchParams function completley and just write the search parameters manually. If anyone else knows how to fix this issue while still using URLSearchParams please let me know.

Before
body: new URLSearchParams({
        grant_type: 'refresh_token',
        refresh_token,
      })
After
body: `grant_type=refresh_token&refresh_token=${refresh_token}`

Final Code

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `grant_type=refresh_token&refresh_token=${refresh_token}`
  })
  return response.json()
}
  • Related