Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i refetch from a diffrent url using react-Query?

I'm using react query and fetch to get data from the dictionary API I wanted to add a functionality where I can change the value I pull from the API I added an on-click function that changes the state which is a part of the URL and when it triggers a rerender it should give me a new definition for the word in the url. but it's behaving rather slow and it sometimes takes multiple clicks to get it to work which is odd, I'm thinking it has to do with the speed of fetching data but that can't is the case since it returns instantly on the console.

here is my page:

import React from "react";
import { useQuery } from "react-query";
import { useState } from "react";
import { Button } from "@chakra-ui/react";

const Word = () => {
  const [word, setword] = useState("run");
  const handleWordchange = () => {
    if (word === "run") {
      setword("stop");
    } else {
      setword("run");
    }
    console.log(word);
  };

  const fetchWord = async () => {
    const res = await fetch(
      `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`
    );

    return res.json();
  };
  const { data, status, isLoading, isFetching } = useQuery(
    "definition",
    fetchWord
  );

  const getDefinition = () => {
    if (isLoading || isFetching) {
      return <h2>is loading</h2>;
    } else {
      let definiton = data[0]["meanings"][0]["definitions"][0]["definition"];
      console.log(data);
      return definiton;
    }
  };

  return (
    <>
      {getDefinition()}
      <Button onClick={handleWordchange}>click</Button>
    </>
  );
};

export default Word;

as you can see very simply all I'm trying to do is get the definition of stop to show up on the screen. on the console, it returns the object

like image 906
flowoverstack Avatar asked Feb 27 '26 06:02

flowoverstack


1 Answers

From the documentation...

If your query function depends on a variable, include it in your query key

Since query keys uniquely describe the data they are fetching, they should include any variables you use in your query function that change

First, I'd move fetchWord out of your component and change it to accept the word parameter. This means it won't be redefined every time your component re-renders and also makes testing much easier.

const baseUrl = "https://api.dictionaryapi.dev/api/v2/entries/en/";

const fetchWord = async (word) => {
  const url = new URL(encodeURIComponent(word), baseUrl);
  const res = await fetch(url);

  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }

  return res.json();
};

Then in your component, add word to the query key and pass it to the fetchWord function

const [word, setword] = useState("run");

const { data, status, isLoading, isFetching } = useQuery(
  ["definition", word],
  () => fetchWord(word)
);
like image 149
Phil Avatar answered Mar 01 '26 22:03

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!