From 52c8cd8d1ccafd8a52bfac31cff7af9039141b80 Mon Sep 17 00:00:00 2001 From: yude Date: Sat, 11 Dec 2021 21:13:44 +0900 Subject: [PATCH] Fix: Discord playing data fetching --- pages/components/Discord/DiscordPlaying.js | 61 ++++++++++------------ 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/pages/components/Discord/DiscordPlaying.js b/pages/components/Discord/DiscordPlaying.js index 36fef77..18009de 100644 --- a/pages/components/Discord/DiscordPlaying.js +++ b/pages/components/Discord/DiscordPlaying.js @@ -2,44 +2,37 @@ import React, { useState, useEffect } from 'react'; // Data fetching -import axios from 'axios'; +import useSwr from 'swr' +const fetcher = (url) => fetch(url).then((res) => res.json()) // i18n import { useTranslation, useLanguageQuery } from 'next-export-i18n'; -function App (){ - const [data, setData] = useState({ hits: [] }); - useEffect(() => { - const fetchData = async () => { - const result = await axios( - 'https://discord.com/api/guilds/723409709306216498/widget.json', - ); - setData(result.data); - }; - fetchData(); - }, []); - if (data === undefined){ - console.log("[Discord API] データの取得に失敗しました。 / Failed to retrieve data.") - return

- }else{ - const str = JSON.stringify(data) +export default function DiscordPlaying() { + const { t } = useTranslation(); + const [query] = useLanguageQuery(); - if (str.indexOf("game") !== -1){ - const yes_playing = t('yes_playing', {playing: data.members[0].game.name}) - return

{yes_playing}

- }else{ - return <> - } + const { data, error } = useSwr( + `https://discord.com/api/guilds/723409709306216498/widget.json`, + fetcher + ) + if (error){ + console.log("[Discord API] データの取得に失敗しました。 / Failed to retrieve data.") + return <> + } else { + if (!data) { + return

Loading...

+ } else { + if (data.members) { + if (data.members[0].game) { + const yes_playing = t('yes_playing', {playing: data.members[0].game.name}) + return

{yes_playing}

+ } else { + return <> + } + } else { + return <> + } + } } -}; - -export async function getServerSideProps() { - // Fetch data from external API - const res = await fetch(url) - const data = await res.json() - - // Pass data to the page via props - return { props: { data } } } - -export default App; \ No newline at end of file