json-server
Appディレクトリ内でJson Serverをローカルインストール
npm install json-server
package.jsonと同階層にdb.jsonを新規作成
{
"posts": [
{"id": 1, "title": "TITLE1", "author": "AUTHOR1"},
{"id": 2, "title": "TITLE2", "author": "AUTHOR2"}
],
"comments": [{"id": 1, "body": "BODY1", "postId": 1}],
"profile": {"name": "NAME1"}
}
json-serverの立ち上げ
json-serverをグローバルインストールしていれば次のコマンドで立ち上げられるが、
json-server --watch db.json
ローカルインストールの場合は、package.jsonの中に次のコードを追記してあげる
"scripts": {
"json-server": "json-server --watch db.json --port 3001"
}
そして次のコマンドで立ち上げられる
npm run json-server
json-serverのデータを取得
import { useState, useCallback, useEffect } from 'react';
const [title, setTitle] = useState("");
const getPostTitle = useCallback(async ()=>{
const res = await fetch("http://localhost:3001/posts?author=%E3%81---");
const json = await res.json();
setTitle(json[0].title); <--Jsonは配列として入っているので[0]が必要
}, []);
useEffect( ()=>{
getPostTitle();
}, []);
return (
<h1>{title}</h1>
);
※useCallbackはReact hooksの一つであり、useEffectと同じように、依存配列が変化したときのみ、値を計算する、という機能
※fetch()したdb.jsonはJSON形式で書かれているので、.json()してデータを取得する
※res.json()の前にawaitをつけないと「TypeError: Cannot read properties of undefined」というエラーが起きる
※ローカルサーバーの場合はこれでうまく行ったが、レンタルサーバーにJsonファイルをアップする場合は、CORSを作成しないといけないかも(https://qiita.com/redrabbit1104/items/806ef9849f4b0962ceaa)
BACK