use-postal-jp
Version:
郵便番号を住所に変換するReactカスタムフックです。住所データを内部に持たず、APIで住所変換するため軽量なパッケージになっています。
55 lines (54 loc) • 1.74 kB
JavaScript
import { useState, useEffect } from "react";
var endpoint = {
api: "https://madefor.github.io/postal-code-api/api/v1/"
};
const sanitize = (code) => {
const sanitized = `${code}`.replace(/[^0-90-9]/g, "").replace(/[0-9]/g, (s) => String.fromCharCode(s.charCodeAt(0) - 65248));
return [sanitized.slice(0, 3), sanitized.slice(3, 7)];
};
const makeRequestURL = ([first, second]) => `${endpoint.api}${first}/${second}.json`;
const parseResponse = (res) => {
const {
data: [{ prefcode, ja: data }]
} = res;
return {
prefectureCode: prefcode,
prefecture: data.prefecture,
address1: data.address1,
address2: data.address2,
address3: data.address3,
address4: data.address4
};
};
const usePostalJp = (postalCode, ready, option) => {
var _a, _b;
const url = (_a = option == null ? void 0 : option.url) != null ? _a : makeRequestURL;
const parse = (_b = option == null ? void 0 : option.parse) != null ? _b : parseResponse;
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [address, setAddress] = useState(null);
useEffect(() => {
let mounted = true;
if (!ready)
return;
setLoading(true);
fetch(url(sanitize(postalCode))).then((res) => {
if (!res.ok)
throw new Error("Bad request");
return res.json();
}).then((data) => {
mounted && setAddress(parse(data));
mounted && setError(null);
}).catch((e) => {
mounted && setAddress(null);
mounted && setError(e);
}).finally(() => {
mounted && setLoading(false);
});
return () => {
mounted = false;
};
}, [postalCode, ready]);
return [address, loading, error];
};
export { usePostalJp };