Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading