React Typescript - Can't pass fetch response to child component [hooks, functionalComponent]

Viewed 168

I have been trying to pass the response object from making a fetch request to a child component of a functional component. The simplified code to do this in the parent component is as follows:

 <Datatable data={response} />

The idea is then inside the child component to map over all the statusCode and statusText entries for each request made by the Fecth API and create a new row in a table. Should be easy right?

However, I can't understand the error message I'm getting Type 'RequestProps | undefined' is not assignable to type 'RequestProps[]'. Type 'undefined' is not assignable to type 'RequestProps[]'. For context I have defined two types one to have the type for a response and then a type for an array of these types as follows:

type RequestProps = {
  status: number;
  statusText: string;
}

type Props = {
  data: RequestProps[]; 
}

I have a sandbox environment here for testing.

1 Answers

Your initial value is RequestProps[] | undefined, to fix it add a specific initial type (a RequestProps[] type only):

// response type is `RequestProps[] | undefined`
  const [response, setResponse] = useState<RequestProps[]>();

// Add an initial value (an empty array `[]`)
  const [response, setResponse] = useState<RequestProps[]>([]);

Edit blue-sound-d0h7o

Related