Search code examples
javascriptnext.jsknex.jsswr

Strange query bug with Next js, Knex, and SWR


Using Next API routes and Knex + MySQL, and using React and SWR for fetching, I get a strange bug. If a request fails, my queries start appending , * to the select statement, resulting in SQL syntax errors. For example, the query should use select *, but comes out as select *, * and then select *, *, * and so on. Does anyone have any idea why this might happen?

SWR fetch:

export const swrFetcher = async (...args) => {
  const [url, contentType = 'application/json'] = args;
  const res = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': contentType,
    },
  });
  if (!res.ok) throw new Error(res.statusText);
  const json = await res.json();
  return json;
};

const { data, error } = useSWR('/api/user/me', swrFetcher, {
    revalidateOnFocus: false,
    revalidateOnReconnect: false,
    revalidateOnMount: true,
  });

knex query:

const User = knex(TABLE_NAMES.user);
export const readById = (id) => User.select('*').where({ id });

Solution

  • You probably need to create the knex instance within the function call and not reuse the same every time, like it's currently happening.

    export const readById = (id) => {
        const User = knex(TABLE_NAMES.user);
        return User.select('*').where({ id });
    }