Yogendra
Yogendra

Reputation: 73

Argument of type 'Response' is not assignable to parameter of type 'SetStateAction`

This is my CommentResponse interface, which is the structure of an object inside the array from API response

interface CommentResponse {
  body: string;
  email: string;
  id: number;
  name: string;
  postId: number;
}

While setting the data from the API response using setAllComments (useState-hook), I'm getting the following error

/typescript-demo/src/components/Dashboard/index.tsx
TypeScript error in /typescript-demo/src/components/Dashboard/index.tsx(35,20):
Argument of type 'Response' is not assignable to parameter of type 'SetStateAction<CommentResponse[]>'.
  Type 'Response' is missing the following properties from type 'CommentResponse[]': length, pop, push, concat, and 28 more.  TS2345
    32 |     comments = await comments.json();
    33 |     console.log(comments);
    34 |     // comments = await JSON.parse(comments);
  > 35 |     setAllComments(comments);
       |                    ^
    36 |   };
    37 | 
    38 |   useEffect(() => {

@RajaJaganathan

const [allComments, setAllComments] = useState<CommentResponse[]>([]);

  const commentService = async () => {
    const COMMENTS_API = `https://jsonplaceholder.typicode.com/comments`;    
    let comments = await fetch<Array<CommentResponse>>(COMMENTS_API);

    comments = await comments.json();
    console.log(comments);

    setAllComments(comments);
  };

I visited other StackOverflow & Google links, but couldn't get the solution

Upvotes: 2

Views: 5369

Answers (2)

Jagannath Swarnkar
Jagannath Swarnkar

Reputation: 369

In your case response from fetch it is returning an object with Object type which has values as Response {type: "cors", url: "https://jsonplaceholder.typicode.com/comments", redirected: false, status: 200…}

get your interface at right place :

const COMMENTS_API = `https://jsonplaceholder.typicode.com/comments`;    
let comments =  await fetch(COMMENTS_API);

let result: Array<CommentResponse> = await comments.json();

setAllComments(result);

you can use both type result:Array<CommentResponse> or result:CommentResponse[].

check code demo here for both fetch and axios.

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370979

It sounds like comments is a Response object. To extract the value from it, you'll need to call .json() on it.

It looks like the generic from .json was removed, so you'll have to use type assertion:

fetch('some-api')
  .then(res => res.json())
  .then(comments => setAllComments(comments as Array<CommentResponse>))
  .catch(handleErrors);

Upvotes: 3

Related Questions