環境
Amazon linux AMI
React.js 16.8.6
Typescript 3.5.2
実現したい事
▼現状(APIからjsonで情報を受け取る)
interface State { products: any[], } class Hoge extends React.Component<{}, State> { constructor(props: any) { super(props); this.state = { products: [] }; } async componentDidMount() { //=====ここのAPIの情報とってくる部分を関数化したい===== const response = await fetch('/api/hoge', { method: POST, }); const products = await response.json(); this.setState({ products }); } render() { return ( <div className="hoge"> //省略 </div> ); } } export default Hoge;
▼試してみたコード
import apiConnect from '../common/ApiConnect';//**追加 interface State { products: any[], } class Hoge extends React.Component<{}, State> { constructor(props: any) { super(props); this.state = { products: [] }; } async componentDidMount() { const products = apiConnect('/api/hoge', 'POST')//**変更 this.setState({ products }); } render() { return ( <div className="hoge"> //省略 </div> ); } } export default Hoge;
▼apiConnect.tsx
const apiConnect = async function(url: string, method: string) { const response = await fetch(url, { method: method, }); const data = await response.json(); return data; } export default apiConnect;
困っていること、質問
①apiConnect関数ではjson()を使用しているのに、Promiseがreturnされるのはなぜか?
②①のせいでsetStateで値を更新できないが、この場合どう対処したら良いのか?
よろしくお願いいたします。
回答3件
あなたの回答
tips
プレビュー