What should be used for data fetching in Next.js: SWR or traditional fetch/axios along with useEffect?

I'm currently diving into the world of Next.js and I'm eager to showcase data based on user input queries. However, I'm uncertain if leveraging useSWR is the most suitable approach to tackle this challenge because I haven't come across any examples illustrating what I'm attempting to achieve.

Here's a glimpse of my code:

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>
    </>
  );
}

Could anyone confirm if my implementation of useSWR is appropriate or would it be more effective to stick with a conventional fetch method paired with useEffect?

Answer №1

In my opinion, I highly recommend utilizing useSWR due to the endorsement from the developers at Next.js; in contrast, useEffect is solely a react hook.

The simplicity of the useSWR logic is remarkable, requiring minimal code. Moreover, the availability of various optional parameters such as revalidateOnRender can greatly aid in the development process.

For instance, consider the example from the documentation:

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>
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

How can I utilize React hook to choose multiple items?

I am currently working on developing a next js application. As part of this project, I have been tasked with creating a custom dropdown select menu using react hooks, specifically useState. The code I have written for this is as follows. Data- export defa ...

What is the best way to pass the setState value to the useEffect hook?

After watching a Youtube video, I took on the challenge of creating my own recipe app using React.js as a beginner. I have been troubleshooting for the past 2 days and seem to have hit a roadblock. The issue lies in passing the value of my state to the use ...

Python.Selenium. Unable to locate current element. Techniques for switching frames

I am trying to collect feedback from a specific page at this URL. After waiting for the page to load, I attempted to locate elements using Google Chrome inspector. However, Selenium is unable to find these elements, and I also could not find them in the p ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

What purpose does @ViewChild serve if we are unable to modify or interact with its properties from the Parent Component?

I have two main components - home and about. Within both of these, I am including a third component called hearts. Currently, I am manipulating the value of the 'age' property in the hearts component (initially set to '23') using @ViewC ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

What is the proper way to generate an iframe with a width set to "100%" or left empty, rather than width = "100"?

I am currently utilizing vimeowrap to iterate through a playlist of videos. I would like the iframe that is generated by vimeowrap to have either a width and height set to "100%" or nothing at all. For more information on Vimeo Wrap, visit: To see my tes ...

Utilizing Ajax to dynamically generate unique ID's for multiple checkboxes

I have been working on a website that is almost completed, however, I have come across a new task where I need to select check-boxes in order to archive news items or "blog posts". The concept is to have a check-box next to each blog post and by checking ...

Exploring the KEY attributes within a JSON dataset

In my React project, I am working on displaying specific key values from a JSON response. For example, the fieldData {DMR_5_why_who_test: "test", why: test}. My goal is to only show the bolded or key values in my output. However, my current code is not a ...

I noticed a change in the state between dispatches, but I did not make any alterations to the state

Although this question has been previously raised, most of the discussions focus on the OP directly mutating the state. I have taken precautions to avoid this by using techniques like the spread operator with objects and arrays. However, despite these effo ...

Tips for implementing authorization in a NextJS API Backend

I currently have a Next.js app that is utilizing Prisma as the ORM. One of my pages, /somecats, connects to the Next.js backend (/pages/api/categories). I noticed that when I access http://localhost:3000/api/requests, it does not require any authorization. ...

Thumbnail for Reddit link not displaying due to dynamic OG:image issue

I am currently working on a NextJS app that allows users to share links to Reddit. The issue I am facing is that the link preview in Reddit always shows the same thumbnail image, regardless of the shared link. Interestingly, this problem does not occur whe ...

The show-word-limit feature is malfunctioning on the element.eleme.io platform

After attempting to utilize the show-word-limit attribute of the input element, unfortunately the character count did not display. Below is the code snippet that was used: <el-input type="textarea" placeholder="Please input" ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

Similar to AngularJS, jQuery also provides a powerful tool for submitting forms

Recently, I've delved into the world of angularjs and have been truly amazed by its capabilities so far. One thing that took me by surprise was the lack of a simple solution for sending AJAX requests using the $http service. After hours of searching G ...

Click event triggering smooth scrolling

I am currently working on implementing a smooth scrolling effect using the React JavaScript library without relying on jQuery. My goal is to ensure that when a user clicks on a link, they are directed to the specific section of the page seamlessly. The f ...

JSON data being sent through an AJAX request

Currently, I am developing a chat system that automatically refreshes using AJAX. Initially, I utilized the jQuery $.post function which worked fine for my needs. However, since I required JSON data from my PHP script, I switched to using the $.ajax functi ...