0

Hi I'm new to typescript react and ionic and I'm getting this error on the title, and the error Argument of type '{ artist: string; title: string; uri: string; albumUrl: string; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'. in my return I'm trying to convert a javascript project to a typescript with ionic react

useEffect(() => {
    if (!search) return setSearchResults([])
    if (!accessToken) return

    let cancel = false
    spotifyApi.searchTracks(search).then(res => {
      if (cancel) return
      setSearchResults(
        res.body.tracks.items.map(track => {
          const smallestAlbumImage = track.album.images.reduce(
            (smallest, image) => {
              if (image.height < smallest.height) return image
              return smallest
            },
            track.album.images[0]
          )

          return {
            artist: track.artists[0].name,
            title: track.name,
            uri: track.uri,
            albumUrl: smallestAlbumImage.url,
          }
        })
      )
    })

    return () => (cancel = true)
  }, [search, accessToken])

I found other similar cases but I couldn't apply to my code, since I could barely understand, pls help

  • Why are you returning `setSearchResults([])` on the first line of the effect function? What do you expect that to do? – JLRishe Jun 22 '23 at 06:03
  • if search were to be null, so it would return a empty array – William Vieira Jun 22 '23 at 06:35
  • Return it to where? Presumably `setSearchResults` is a `useState` setter, so you are using it to set an empty array to the state. But why do you have the word `return` before it? – JLRishe Jun 25 '23 at 17:05

1 Answers1

0

Because the setup function and cleanup function in useEffect hook are only allowed to return void. See types below

// setup function
type EffectCallback = () => (void | Destructor);

// cleanup function
// Destructors are only allowed to return void.
type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never };

Besides, the assignment operation evaluates to the assigned value. That's why the return value of const cleanup = () => (cancel = true) is true rather than void. See Assignment (=) and Value returned by the assignment

useEffect(() => {
  if (!search) {
    setSearchResults([]);
    return;
  }
  //...
  return () => {
    cancel = true;
  }
}}

stackblitz

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • To clarify this a bit better, I'd highlight that it's important to understand that `() => (cancel = true)` is actually shorthand for `() => { return cancel = true }` (a `() => boolean`) rather than `() => { cancel = true }` (a `() => void`). – samthecodingman Jun 22 '23 at 09:52