I use graphql and swr to fetch data
and this is my fetcher:
FetcherHelper.js
const ENDPOINT = "/api/graphql";
const headers = { 'Content-Type': 'application/json' };
export default async function FetchHelper({query}) {
const options = {
headers: headers,
method: 'POST',
body: JSON.stringify({query})
};
const res = await fetch(ENDPOINT, options)
const res_json = await res.json();
if (res_json.errors) {
throw (JSON.stringify(res_json.errors));
}
return res_json.data;
}
and this is how I use SWR
const QUERY_GET_DATA = gql`
query GETDATA{
getUsers{
id
first_name
last_name
}
}
`;
const getData = async (query) => {
const response = await FetchHelper({query});
console.log('get Data : ', response);
return response;;
};
the response log:
{
"data": {
"getUsers": [
{
"id": "6d9cb858-43e9-473e-84a4-7766095b",
"first_name": null,
"last_name": null
},
{
"id": "7ce9a327-a4dd-43a3-af8d-53ee87e7",
"first_name": null,
"last_name": null
}
]
}
}
and I use SWR in component like this:
const { dataForForm, error } = useSWR(QUERY_GET_DATA, getData);
if (error) return <div>failed to load</div>
if (!dataForForm) return <div>loading...</div>
console.log(dataForForm); <-- never executed
it stuck in loading...
but it stuck in loading, dataForForm
never populated.
why this happend and how to solve this?