Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data is always undefined even if the request is successful? (SWR + Next.js) #411

Closed
thejonmonte opened this issue May 28, 2020 · 2 comments

Comments

@thejonmonte
Copy link

Hi, I'm using SWR with Next.js, which I'm both extremely new to, and I've been trying to fetch data from a URL with useSWR. However, even if there exists response data from the fetcher, the data returned from useSWR is still always undefined and my application always displays "loading...". Below is a snippet of the code relating to this:

const HomePage = memo(props => {
    const { data, error } = useSWR(url, fetcher({ query: {} }));

    if (error) return <div>failed to load</div>;
    if (!data) return <div>loading...</div>;
...

Fetcher function:

const url = `${process.env.baseUrl}/...`;

const fetcher = (queryBody) =>
    fetch(url, {
        method: 'POST',
        headers: {
            "Accept": 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(queryBody)
    }).then(async (res) => {
        try {
            const response = await res.json();
            return response;
        } catch (error) {
            console.log(error);
        }
    });
@thejonmonte
Copy link
Author

Never mind, I saw #93, specifically monman2l's comment. It made me realize that I needed to change my fetcher function to

const fetcher = queryBody => (url) =>
    fetch(url, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            "Content-Type": "application/json"
        },
        body: JSON.stringify(queryBody)
    }).then(async (res) => {
        try {
            const response = await res.json();
            console.log(response);
            return response;
        } catch (error) {
            console.log(error);
        }
    });

Thank you though!

@sergiodxa
Copy link
Contributor

I also recommend you to not use SWR to do POST requests, only GET

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants