Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

fetch

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

like image 923
Mattèo Gauthier Avatar asked Sep 16 '25 18:09

Mattèo Gauthier


2 Answers

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>
    )
}
like image 148
asmaa Avatar answered Sep 19 '25 08:09

asmaa


In my case I've just added default SWR fetcher function before calling useSWR:

  const fetcher = async (url) => {
    const res = await fetch(url);

    // If the status code is not in the range 200-299,
    // we still try to parse and throw it.
    if (!res.ok) {
      const error = new Error("An error occurred while fetching the data.");
      // Attach extra info to the error object.
      error.info = await res.json();
      error.status = res.status;
      throw error;
    }

    return res.json();
  };

I than used it:

const { data, error } = useSWR(url, fetch)

And behold, loading...'s gonne and date is here :)

like image 39
Hrvoje Avatar answered Sep 19 '25 07:09

Hrvoje