Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

395
Views
useSWR returning undefined data with axios in nextjs

I have a useSubjects custom hook to fetch the data from my API endpoint that utilizes useSWR.

import axios from '@/lib/axios'
import useSWR from 'swr'

/**
 * Fetcher Function for SWR
 */
const fetchSubjects = async url => {
    console.log("url = " + url)
    await axios
        .get(url)
        .then(res => res.data)
        .catch(error => {
            if (error.response.status !== 409) throw error
        })
}

export const useSubjects = (id = -1) => {
    // /**
    //  * swr hook for fetching subjects
    //  */
    const { data: subjects, error, mutate } = useSWR(
        id > 0 ? `api/get-subject-branch/${id}` : 'api/get-subject-branches',
        fetchSubjects,
    )

    return {
        subjects,
        error,
    }
}

The useSubjects hook is later used in one of my components.

import { useEffect } from 'react'
import { useSubjects } from '@/hooks/subjects'

const myComponent = () => {
   const { subjects, error } = useSubjects()

    useEffect(() => {
        console.log(subjects)
    }, [subjects])

   return (
      <>
         <div>My Content</div>
      </>
   )
}

However, the constant {subjects} which should hold the fetched data from the useSWR hook seems to remain undefined

I have tested out my API endpoint using direct axios GET request and it successfully pulls the data from my API.

In fact, I have written console.log(res.data) in my fetchSubjects fetcher function that seems to get the data. But it is somehow it is not setting the const {data: subjects, ...} that should hold the data fetched from the API and it remains undefined

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are not returning anything from the fetcher , it should be

const fetchSubjects = async (url: string) => {
    console.log("url = " + url)
     return await axios
        .get(url)
        .then(res => res.data)
        .catch(error => {
            if (error.response.status !== 409) throw error
        })
}

check this working example https://codesandbox.io/s/swr-axios-forked-r4loo6

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!