currently i'm practice react-ts fetching json data via async fetcher
sample code is below like this
//Test.tsx
import React, { useState, useEffect } from 'react';
import fetcher from 'api/fetcher';
interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
const Test: React.FC = () => {
const [data, setData] = useState<Todo[]| Promise<Todo[]>>([{
userId: 1,
id: 1234,
title: "test",
completed: false
}]);
useEffect(() => {
const result = fetcher("https://jsonplaceholder.typicode.com/todos");
setData(result);
console.log(result);
}, [])
return (
<div>
//error in here
**{data && data.map()}**
{/* {data && data.map((item: Todo)=> {
<div>{item.id}<div>
})} */}
</div>
);
}
export default Test;
//fetcher.ts
async function fetcher(url: RequestInfo) {
try {
const res = await fetch(url);
const json = await res.json();
console.log("json: ", json);
return json;
} catch (e) {
throw e;
}
}
export default fetcher;
Error Message : Property 'map' does not exist on type 'Todo[] | Promise'. Property 'map' does not exist on type 'Promise'
i know map method can't using at Promise Object. due to async call, initial data type is set to be Promise type, and switched to Todo[] when fetch resolved.
how to solve this problem to use map method dynamically