0
import {Address} from './address.model';
export const get = async ():Promise<Address[]>    =>  {  
  
  return await fetch(`${apiUrl}`)
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText)
    }
    return   response.json() as Promise<Address[]>;
  })

//--------------caling from
 React.useEffect(() => {
    let newArr: Address[] = get()  ;
     setEntities(newArr);
  } , [])

//-------------throws following error: Type 'Promise<Address[]>' is missing the following properties from type 'Address[]': length, pop, push, concat, and 28 more. TS2740

MPV
  • 337
  • 3
  • 10

1 Answers1

1

Ignoring the problematic casting (cf. as Promise<Address[]>) you'll need to await your get() function to get the Address[] type, so

 React.useEffect(() => {
    async get() => {
     // do the IO
    }
    const newArr: Address[] = await get()
    setEntities(newArr)
  } , [])
BrantApps
  • 6,362
  • 2
  • 27
  • 60
  • Good point. But adding async throws following error: Argument of type '() => Promise' is not assignable to parameter of type 'EffectCallback'. Type 'Promise' is not assignable to type 'void | (() => void | undefined)'. Type 'Promise' is not assignable to type '() => void | undefined'. Type 'Promise' provides no match for the signature '(): void | undefined'. TS2345 – MPV Jun 29 '20 at 00:23
  • async inside useEffect need to like this : https://stackoverflow.com/questions/56838392/how-to-call-an-async-function-inside-a-useeffect-in-react . I'll go ahead make change in the answer. – MPV Jun 29 '20 at 00:59
  • Ah yes, I always make this mistake. I'll update my code block to match for the next person. – BrantApps Jul 04 '20 at 18:44