In the fisrt part I ma suign fetch() and it is working fine but whe i use useSWR() it returns UNDEFINED
export const getAllEvents = async()=>{
const response = await fetch('https://*******-rtdb.firebaseio.com/events.json');
const data = await response.json();
const events = [];
for (const key in data){
events.push({
id:key,
...data[key]
});
}
return events; // returns data as I wanted.. perfect
}
but in the following snippet it returns undefined (the same url)
import useSWR from 'swr';
const {data, error} = useSWR('https://*******-rtdb.firebaseio.com/events.json');
console.log(data); // returns undefined
CodePudding user response:
useSWR
expects fetcher
function as second argument:
https://swr.vercel.app/#overview
It can be a custom method e.g.
export const fetcher = async (...args: Parameters<typeof fetch>) => {
const res = await fetch(...args);
if (!res.ok) {
throw { status: res.status, statusText: res.statusText };
}
return res.json();
};
CodePudding user response:
Use swr also needs to take a fetcher function, right now you're just passing down a url. Swr doesnt know what to do with that url..
const { data, error } = useSWR(
"https://api.github.com/repos/vercel/swr",
fetcher
);
const fetcher = (url) => fetch(url).then((res) => res.json());
I suggest you read the docs.
CodePudding user response:
add this :
const fetcher = (...args) => fetch(...args).then(res => res.json())
const {data, error} = useSWR('https://*******-rtdb.firebaseio.com/events.json', fetcher);