skip to Main Content

I am doing:

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

However, the error:

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

May I ask how I can solve it?

2

Answers


  1. Check data before executing find() method on it.

    const {data, error} = useSWR("api/data", fetcher, {refreshInterval: 10000});
    
    // check for error
    if(error) return <h1>`Something went wrong: ${error}`</h1>
    
    // if data is not available, return
    if(!data) return <h1>Loading...</h1>
    
    console.log(data.find(d => d.id === "123"));
    
    Login or Signup to reply.
  2. Try to use filter() method on array

    Try this….

    const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000})
    console.log(data?.filter(d => d.id === "123"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search