Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

336
Visualizações
Next.js data fetching useSWR or regular fetch/axios with useEffect?

I'm learning Next.js and want to show data depending on the query that a user inputs. I want to make use of the features of Next but I'm not sure if useSWR is the correct way of handling this because I couldn't find any examples of what I'm trying to do.

My code looks like this:

export default function SearchBar() {
  const [query, setQuery] = useState("");
  const [address, setAddress] = useState("");
  const fetcher = async (url) => await axios.get(url).then((res) => res.data);
  const { data, error } = useSWR(address, fetcher);

  const handleSubmit = (e) => {
    setAddress(`https://jsonplaceholder.typicode.com/todos/${query}`);
    e.preventDefault();
  };

  if (error) return <div>ERROR</div>;

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Input
          type="text"
          onChange={(e) => setQuery(e.target.value)}
          value={query}
        />
        <SearchButton type="submit">Search</SearchButton>
      </Form>
    </>
  );
}

Is this correct usage of useSWR or should I just use a normal fetch with useEffect?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Personally, I recommend using useSWR as it's recommended by Next.js developers; useEffect is pure react hook.

The logic of useSWR is very simple, don't need to write a lot of code. In addition, you have a lot of option params as revalidateOnRender which will be very useful in development.

Example from docs:

function Profile() {
  const { data, error } = useSWR('/api/user')

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda