Home > database >  Cannot map results from API
Cannot map results from API

Time:01-04

I'm trying to dynamically generate routes in my next.js application. I have an api called getUsers that returns something like this:

{"users":[{"_id":"639a87ae8a128118cecae85b","username":"STCollier","image":"https://storage.googleapis.com/replit/images/1641322468533_db666b7453a6efdb886f0625aa9ea987.jpeg","admin":false,"likedPosts":["639e34c5991ecaea52ace9e4","639e34c7991ecaea52ace9e7","639e34c7991ecaea52ace9ea","639e39a216a642f686a28036","639e39a216a642f686a28037","639e3b3d8cdebd89d9691f97","639e3b3d8cdebd89d9691f98","639e3b3e8cdebd89d9691f9d","639e3b5a8cdebd89d9691fa0","639e3b5c8cdebd89d9691fa3","639e3b5c8cdebd89d9691fa6"],"dislikedPosts":[""]},{"_id":"639a88abc4274fba4e775cbe","username":"IcemasterEric","image":"https://storage.googleapis.com/replit/images/1646785533195_169db2a072ad275cfd18a9c2a9cd78a1.jpeg","admin":false,"likedPosts":[],"dislikedPosts":[]}

So I know the API works succesfully, but when trying to get these api results and generate a page for each username, I get an error stating:

TypeError: users.map is not a function

Here's my code for generating the routes:

//pages/user/[username].js

const Get = async (url) => {
  return await fetch(url).then(r => r.json());
}

export async function getStaticPaths() {
  const users = Get('/api/getUsers')
  return {
    paths: users.map(u => {
      const username = u.users.username
      
      return {
        params: {
          username
        }
      }
    }),
    fallback: false
  }
}

What is wrong with my getStaticPaths() code? I know that the API is working, so why can't I map the results?

And if anyone needs the code for api/getUsers, here is that:

import clientPromise from "../../lib/mongodb";
import nc from "next-connect";

const app = nc()

app.get(async function getUsers(req, res) {
  const client = await clientPromise;
  const db = client.db("the-quotes-place");
  let users = []
  
  try {
    const dbUsers = await db
      .collection("users")
      .find({})
      .toArray();

    users = dbUsers

    return res.json({
      users: JSON.parse(JSON.stringify(users)),
      success: true
    })
  } catch(e) {
    return res.json({
      message: new Error(e).message,
      success: false,
    });
  }
})

export default app

Thanks for any help!!

CodePudding user response:

  1. Modify Get method to return an async value instead of Promise.

  2. As Get is an async method, you need the await in getStaticPaths method.

const Get = async (url) => {
  let response = await fetch(url);
  return await response.json();
}

export async function getStaticPaths() {
  const users = await Get('/api/getUsers');
  ...
}
  • Related