Support basePath in all queries.

This commit is contained in:
Mike Cao 2020-09-30 22:34:16 -07:00
parent 2508198a51
commit 5068ab12a9
11 changed files with 57 additions and 29 deletions

View file

@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { get } from 'lib/web';
import enUS from 'public/country/en-US.json';
@ -8,9 +9,10 @@ const countryNames = {
export default function useCountryNames(locale) {
const [list, setList] = useState(countryNames[locale] || enUS);
const { basePath } = useRouter();
async function loadData(locale) {
const { ok, data } = await get(`/country/${locale}.json`);
const { ok, data } = await get(`${basePath}/country/${locale}.json`);
if (ok) {
countryNames[locale] = data;

View file

@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { get } from 'lib/web';
import { updateQuery } from 'redux/actions/queries';
import { useRouter } from 'next/router';
export default function useFetch(url, params = {}, options = {}) {
const dispatch = useDispatch();
@ -9,6 +10,7 @@ export default function useFetch(url, params = {}, options = {}) {
const [status, setStatus] = useState();
const [error, setError] = useState();
const [loading, setLoadiing] = useState(false);
const { basePath } = useRouter();
const keys = Object.keys(params)
.sort()
.map(key => params[key]);
@ -19,7 +21,7 @@ export default function useFetch(url, params = {}, options = {}) {
setLoadiing(true);
setError(null);
const time = performance.now();
const { data, status } = await get(url, params);
const { data, status } = await get(`${basePath}${url}`, params);
dispatch(updateQuery({ url, time: performance.now() - time, completed: Date.now() }));

View file

@ -1,6 +1,8 @@
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from 'redux/actions/user';
import { useRouter } from 'next/router';
import { get } from '../lib/web';
export async function fetchUser() {
const res = await fetch('/api/auth/verify');
@ -13,29 +15,33 @@ export async function fetchUser() {
}
export default function useRequireLogin() {
const router = useRouter();
const dispatch = useDispatch();
const storeUser = useSelector(state => state.user);
const [loading, setLoading] = useState(!storeUser);
const [user, setUser] = useState(storeUser);
async function loadUser() {
setLoading(true);
const { ok, data } = await get(`${router.basePath}/api/auth/verify`);
if (!ok) {
return router.push('/login');
}
await dispatch(updateUser(data));
setUser(user);
setLoading(false);
}
useEffect(() => {
if (!loading && user) {
return;
}
setLoading(true);
fetchUser().then(async user => {
if (!user) {
window.location.href = '/login';
return;
}
await dispatch(updateUser(user));
setUser(user);
setLoading(false);
});
loadUser();
}, []);
return { user, loading };