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
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>
)
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With