0

Since on first render I was not able to get the router.query I am passing the params from getServerSideProps as follows:

export async function getServerSideProps(context) {
    return {
        props: { params: context.params },
    };
}

Then in the function am trying to do the API call but am getting the API stalled error

API resolved without sending a response for /api/projects/nichole_robel23, this may result in stalled requests.

This is my code:

export default function Project({ params }) {
    const { slug } = params;

    let [projectData, setProjectData] = useState([]);
    let [loading, setLoading] = useState(true);

    const { data } = useSWR('http://localhost:3000/api/projects/' + slug);

    useEffect(() => {
        if (data) {
            setProjectData(data.data.project);
            setLoading(false);
        }
    }, [data]);

......

I have global SWRCofig as follows

<SWRConfig value={{ fetcher: (url) => axios(url).then(r => r.data) }}>
                        <Layout>
                            <Component {...pageProps} />
                        </Layout>
                    </SWRConfig>

Any way to solve the problem?

Harsha M V
  • 54,075
  • 125
  • 354
  • 529

1 Answers1

3

You are missing your fetcher–the function that accepts the key of SWR and returns the data, so the API is not being called.

You are also not returning a response correctly from the API–this is most likely a case of not waiting for a promise/async to be fulfilled correctly.

CLIENT

const fetcher = (...args) => fetch(...args).then((res) => res.json());

export default function Home({ params }) {
  const { slug } = params;
  const [projectData, setProjectData] = useState([]);
  const [loading, setLoading] = useState(true);

  const { data } = useSWR(`http://localhost:3000/api/projects/${slug}`, fetcher);

  useEffect(() => {
    if (data) {
      setProjectData(data);
      setLoading(false);
    }
  }, [data]);

API

const getData = () => {
  return new Promise((resolve, reject) => {
    // simulate delay
    setTimeout(() => {
      return resolve([{ name: 'luke' }, { name: 'darth' }]);
    }, 2000);
  });
}

export default async (req, res) => {
  // below will result in: API resolved without sending a response for /api/projects/vader, this may result in stalled requests
  // getData()
  //   .then((data) => {
  //     res.status(200).json(data);
  //   });

  // better
  const data = await getData();
  res.status(200).json(data);
}
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104