Next.js Discord

Discord Forum

data fetching on client side on button press using input value

Unanswered
Pacific anchoveta posted this in #help-forum
Open in Discord
Pacific anchovetaOP
Hello there! I'm working an on application where you can search up your game stats for a mc server, but before routing the user to the correct page I want to fetch the mc id to make sure the given value is an exisiting minecraft account.
"use client"
import Image from "next/image";
import styles from "./page.module.css";
import { Input, Button } from "@nextui-org/react";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { getData } from "./Util/functions";

import useSWR from "swr";
const fetcher = (...args) => fetch(...args).then((res) => res.json())

export default function Home() {
  const router = useRouter()
  const [inputValue, setInputValue] = useState("");
  const [data, setData] = useState(null)
  const [isLoading, setLoading] = useState(false)
  const [started, setStarted] = useState(false)

  async function handleClick(inputValue) {
    setLoading(true)
    setStarted(true)

    const { data, error } = useSWR(`https://api.mojang.com/users/profiles/minecraft/${inputValue}`, fetcher)

    if (error) return <div>Failed to load</div>
    if (!data && started) return <div>Loading...</div>

    // const profiles = await getData(`https://api.hypixel.net/v2/skyblock/profiles?key=${process.env.HYPIXEL_API_KEY}&uuid=${data.id}`)
    // console.log(profiles, !profiles.profiles?.length)
    // if (!profiles.profiles?.length) return notFound()
    // const selectedProfile = profiles.profiles.filter((profile) => profile.selected)[0]
    // router.push(`/profile/${inputValue}/${selectedProfile.cute_name}`)
  }

  if (isLoading) return <p>Loading...</p>
  if (!data && started) return <p>No profile data</p>

  return (
    <main>
      <Input
        onChange={(event) => setInputValue(event.target.value)}
        type="text" label="Username" />
      <Button
        onClick={() => handleClick(inputValue)}
      >Show Stats</Button>
    </main >
  );
}

2 Replies

Pacific anchovetaOP
I tried using react hooks useEffect, and now also with SWR, but they don't work like this because they're being used in a button onClick action. Any ideas how this can be done?
@Pacific anchoveta I tried using react hooks useEffect, and now also with SWR, but they don't work like this because they're being used in a button onClick action. Any ideas how this can be done?
Sun bear
Your useSwr should not be inside the function. I think you can do it like in the docs:

import useSWR from 'swr'
 
function Profile () {
  const { data, mutate } = useSWR('/api/user', fetcher)
 
  return (
    <div>
      <h1>My name is {data.name}.</h1>
      <button onClick={async () => {
        const newName = data.name.toUpperCase()
        // send a request to the API to update the data
        await requestUpdateUsername(newName)
        // update the local data immediately and revalidate (refetch)
        // NOTE: key is not required when using useSWR's mutate as it's pre-bound
        mutate({ ...data, name: newName })
      }}>Uppercase my name!</button>
    </div>
  )
}