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