Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code:

const fetcher = (url: string) => axios.get(url).then((r) => r.data);

const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000})
console.log(data.find(d => d.id === "123"))

The API path is as follows:

const promises = matchString.split(",").map(async (match: string) => {
    try {
      events.push(await Events.find({ name: match }).then((res) => res[0]))
    } catch (error) {
      events.push(error)
      console.log("model/route.js error")
    }
  })
  await Promise.all(promises)
  return new Response(JSON.stringify(events), { status: 200 });

However, I encountered the error message:

TypeError: Cannot read properties of undefined (reading 'find')

Could someone please help me with resolving this issue?

Answer №1

Always verify the data before using the find() method.

const {data, error} = useSWR("api/data", fetcher, {refreshInterval: 10000});

// check for any errors first
if(error) return <h1>`Oops! Something went wrong: ${error}`</h1>

// if there is no data available yet, show a loading message
if(!data) return <h1>Loading...</h1>

console.log(data.find(d => d.id === "123"));

Answer №2

Experiment with the filter() function to manipulate arrays

Give this a shot...

const {info} = useSWR("api/info", fetcher, {refreshInterval: 10000})
console.log(info?.filter(i => i.id === "456"));

Answer №3

Ensure you consider the loading state in your application. Utilize the useSWR hook which provides an isLoading property to help display a loading indicator while data is being fetched.

Visit the SWR documentation for more information

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
 
  if (error) return <div>failed to load</div>
  if (isLoading) 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

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...

Obtain the Xpath for the element with a certain tag located closest to the given element in its immediate surrounding

Within my HTML document, I have a specific element with an id of uniqueId. There are multiple nested tags surrounding this element, and I am trying to retrieve a particular tag that is closest to it. For example: <div> <div> ...

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...

Is there a way to retrieve the current map center coordinates using the getCenter function in @react-google-maps/api?

I am currently working with the GoogleMap component provided by @react-google-maps/api, but I am struggling to figure out how to obtain the latitude and longitude coordinates of the map's center after it has been moved. After some research, I came ac ...

Looking to generate an HTML table using JavaScript?

Similar Question: Create HTML table from a Javascript array I have received an array that looks like this var univArray = new Array( {name: "Stanford University", nick: "Stanford", ownership: "private", sys: "n/a", SATh: 1550, SATl: 1360, tui ...

Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module. Below is the code for my module which you can review and provide feedback on. var employee = { all: function (req, res) { jwt.verify(req.token, 'novatureso ...

Handling OnClick events in D3 with Websocket Integration

My goal is to implement a Websocket in JavaScript that transmits a variable obtained when clicking on a node in a D3 chart. While I have made progress using static data, I'm struggling with initiating the code upon node click to retrieve the "user inf ...

Retrieve the value of an attribute within a controller function that is not a directive

Here is some HTML content, <button data-href="helloworld">Show href Value</button> And here is some Javascript content, $("body").on('click', 'button', function(){ console.log($(this).attr("data-href")); }); When exe ...

How can I use query to swap out elements within a div when clicked?

I have a project with two separate div classes named demo-heart and demo-coal. The goal is to implement functionality that allows the user to click on the fa-heart icon and have it switch to fa-coal, and vice versa when clicking on fa-coal. <div class ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

Guide on utilizing jQuery/AJAX data with PassportJS

When I submit a login request using the form fields action="/login", method="post", everything works smoothly. This is similar to the code examples found either here or here. However, when I attempt to send the same information using jquery/ajax, passport ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Customize Bootstrap 4 Carousel: Set specific data-interval for each slide

I'm facing an issue with setting the data-interval for each slide of the carousel. I came across a JavaScript code snippet on stackoverflow, but it's not functioning as expected. (Twitter Bootstrap Carousel slide duration) In my HTML, each slide ...

Configuring Access-Control-Allow-Origin does not function properly in AJAX/Node.js interactions

I'm constantly encountering the same issue repeatedly: XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefor ...

jquery module for retrieving and updating messages

I want to develop a custom plugin that can be utilized in a manner similar to the following example. This isn't exactly how I plan to use it, but it serves as the initial test for me to fully grasp its functionality. HTML: <div id="myDiv">< ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...

Is it possible to modify the font size of all text that shares a particular font size?

Lately, I've been pondering on a question. A few years ago, I created a website using regular CSS and now I want to make some changes to the font sizes. While I know that CSS variables are the recommended solution for this situation, I'm curious ...

The function url_for is failing to interpret the variables I am passing to

My goal is to allow users to upload images that are then displayed to all users. The variable "Data" holds the file name (e.g., "files/dog.png"). However, when I try to set the newImg.src value as "{{url_for('static', filename = data )}}", it onl ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...