Search code examples
reactjsfetch

Can't access to my data from a SWR fetch - React


Hello i try to build an app that fetch data from an API. I use SWR Hooks to fetch data

// libs/fetch.js
import fetch from "isomorphic-unfetch"

export default async function(...args) {
  const res = await fetch(...args)
  return res.json()
}
// App.js
import React, { useEffect } from "react"
import "./styles.css"
import useSWR from "swr"
import fetch from './libs/fetch'

export default function App() {
  const url = "https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-stationnement-des-parkings-en-temps-reel&facet=Places_restantes"
  const { data, error } = useSWR(url, fetch)
  return (
    <div className="App">
      {JSON.stringify(data)}
    </div>
  )
}

I cannot access the data value. when i try data.records it returns Cannot read property 'records' of undefined

I don't know what to do, i search but i don't found the answer.

Editor : https://codesandbox.io/s/github/MattixNow/PoitiersParker/tree/80871ba94769346a7008312bdb6e4c1143e591a3

Can someone help me ? Thanks for your reply


Solution

  • according to the docs, you have to handle the error and loading cases

    export default function App() {
        const url =
            "https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-stationnement-des-parkings-en-temps-reel&facet=Places_restantes"
        const { data, error } = useSWR(url, fetch)
    
        if (error) return <div>failed to load</div>
        if (!data) return <div>loading...</div>
    
        return (
            <div className="App">
    
                {JSON.stringify(data.records)}
            </div>
        )
    }