How the component is suppose to work is after typing the input into the search bar and clicking on the enter key, it should show in the console log the json data. It does this, but it lags behind and won't show until clicking the enter key a second time. Next when changing the input in the search bar and clicking the enter key, it'll show the results of the previous search. You won't get the current search until you clicking the enter key again.
For the search bar input, you can use Reinforcements or Contact.
import { Box, Input } from "@chakra-ui/react";
import styles from "../styles/search.module.css";
import React, { useState } from "react";
export default function Search() {
const [cardName, setCardName] = useState("");
const [searchCard, setSearchCard] = useState("");
const handleChange = (event) => {
setCardName(event.target.value);
};
const handleKeyDown = (event) => {
if (event.key == "Enter") {
setSearchCard(cardName);
fetch(`https://db.ygoprodeck.com/api/v7/cardinfo.php?name=${searchCard}`)
.then((response) => response.json())
.then((json) => console.log(json));
}
};
return (
<>
<Box className={styles.container}>
<Input
size="lg"
bg="#e8f1f2"
placeholder="Search for a card"
id="cardName"
name="cardName"
value={cardName}
onChange={handleChange}
onKeyDown={handleKeyDown}
className={styles.input}
></Input>
<ul className={styles.list}></ul>
</Box>
</>
);
}
look at this :
setSearchCard(cardName); // first line
fetch(`https://db.ygoprodeck.com/api/v7/cardinfo.php?name=${searchCard}`) // second line
.then((response) => response.json())
.then((json) => console.log(json));
In the first line you update searchCard
then in the second line you call your API based on searchCard
.
so you expected searchCard
to be updated immediately but this is not how react works the state will be updated only when the component rerenders
so here what you have to do is :
setSearchCard(cardName);
fetch(`https://db.ygoprodeck.com/api/v7/cardinfo.php?name=${cardName}`)
.then((response) => response.json())
.then((json) => console.log(json));
So what is happening is if we suppose that you setCardName("first")
then you call the API (since the component didn't rerendered yet) cardName
is still equal to ''
when the component rerenders (because a useState
hook is updated) and you click again to setCardName("second")
then you call the API (since the component didn't rerendered yet) cardName
is still equal to "first"
that's why you think you have to click twice to get a valid response