I'm trying to develop my first application with Next.js, and there's something happening that is really bothering me.
My app makes 2 requests after first loading, /api/me
and /api/feed
My component fetches the data like this:
useEffect(() => {
async function loadData() {
const res = await fetch('/api/me');
try {
const body = await res.json();
if (body.error) {
return router.push('/login');
}
setUser(body.user);
} catch (e) {
router.push('/login');
}
}
loadData();
}, []);
useEffect(() => {
async function loadFeed() {
const res = await fetch('/api/feed');
const body = await res.json();
console.log('fetch', body.data);
setFeed(body.data);
}
if (user) {
loadFeed();
}
}, [user]);
My problem is, sometimes when it reloads, the responses get mixed up. /feed
returns an array and /me
an object. When reloading, there are times both /feed
and /me
receives the object from /me
, sometimes they both get the array from /feed
, sometimes it works correctly. I didn't find anyone reporting a bug like this, so I'm assuming its a bug somewhere on my part.
/pages/feed/api.js
import handler from '../../helpers/routes/handler';
import auth from '../../middlewares/auth';
import * as feedController from '../../controllers/feed';
export default handler
.use(auth)
.get((req, res) => feedController.get(req, res));
handler.js
import nextConnect from 'next-connect';
import { getSession } from '../../config/passport/encrypt';
const handler = nextConnect()
.use(async (req, res, next) => {
const session = await getSession(req);
if (!session) {
return next();
}
...
next();
});
export default handler;
controllers/feed.js
import * as expertMarketerService from '../services/expert_marketer';
// eslint-disable-next-line import/prefer-default-export
export const get = async (req, res) => {
const data = await expertMarketerService.get(req.user);
return res.status(200).send({ data });
};
pages/api/me.js
import handler from '../../helpers/routes/handler';
import auth from '../../middlewares/auth';
export default handler
.use(auth)
.get((req, res) => res.status(200).send({ user: req.user }));