4

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?

yozawiratama
  • 4,209
  • 12
  • 58
  • 106

1 Answers1

4

Okay I found it

This is my fault, I forget this is destructuring

const { data: dataForForm, error } = useSWR(QUERY_GET_DATA, getData);
  if (error) return <div>failed to load</div>
  if (!dataForForm) return <div>loading...</div>
  console.log(dataForForm); 

return of swr is data, and I forgot to assign it.

Thanks

yozawiratama
  • 4,209
  • 12
  • 58
  • 106