'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.
Can someone help me ? Thanks for your reply
Solution 1:[1]
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>
)
}
Solution 2:[2]
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 :)
Solution 3:[3]
In my case sometimes data were a string sometimes data were an object, i had to change my fetcher to async/await.
Curious thing when data were string it just were missing the closing '}'
export const fetcher = async <T = any>(url: string) => {
const { data } = await api.get<T>(url);
return data;
};
Solution 4:[4]
Before fetch data from the server, JSON.stringify(data.records) were run first or concurrently. An error occurred because it was executed before fetching data from the server.
<div className="App">
{
data&&
JSON.stringify(data.records)
}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | asmaa |
| Solution 2 | Hrvoje |
| Solution 3 | Jonas Mesquita |
| Solution 4 |
