Home > Enterprise >  Input loses focus when changing state in React
Input loses focus when changing state in React

Time:08-02

I am trying to filter through data from the Rick and Morty API that can be found here : https://rickandmortyapi.com/

this is the code I have :

import "./App.css";
import React from "react";
import { useEffect, useState } from "react";
import Card from "./components/Card.js";

function App() {
  const [characters, setCharacters] = useState();
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
  const [query, setQuary] = useState("");

  useEffect(() => {
    const fetchFn = async () => {
      setIsLoading(true);

      try {
        const res = await fetch(
          `https://rickandmortyapi.com/api/character/?name=${query}`
        );
        const data = await res.json();
        setCharacters(data);
      } catch {
        setIsError(true);
      } finally {
        setIsLoading(false);
      }
    };

    fetchFn();
  }, [query]);

  
 

  if (isError) return <div>oops</div>;

  if (isLoading || !characters) return <div>w8 bro</div>;

  const cardList = characters.results.map((character) => {
    return <Card key={character.id} {...character} />;
  });

  return (
    <div className="App">
      <div>
        <form className="input-group rounded">
          <input
            type="text"
            className=""
            placeholder="Search"
            onChange={(e) => setQuary(e.target.value)}
            value={query}
          />
          <button className="btn btn-primary">Search</button>
        </form>
      </div>
      <div className="characters--container">{cardList}</div>
    </div>
  );
}

export default App;

So what I am currently doing is getting the value from the input, and changing the state 'query', that I use on my link to fetch the data. It is working, I get the data that I want, and display them, but every time I type a letter on the input box the cursor stops and I have to click again to type the next letter. Why would this be happening?

CodePudding user response:

You're completely removing the <input> element when you pre-emptively return with if (isLoading || !characters) return <div>w8 bro</div>;

you can fix this by removing that line and changing another

  const cardList = characters?.results.map((character) => {
    return <Card key={character.id} {...character} />;
  });

  return (
    <div className="App">
      <div>
        <form className="input-group rounded">
          <input
            type="text"
            className=""
            placeholder="Search"
            onChange={(e) => setQuary(e.target.value)}
            value={query}
          />
          <button className="btn btn-primary">Search</button>
        </form>
      </div>
      {isLoading || !characters ? (<div>w8 bro</div>) : (<div className="characters--container">{cardList}</div>)}
    </div>
  );

I've made the changes in a CodeSandbox

  • Related