Search code examples
databasenext.jsfaunadb

Can't fetch data in FaunaDB when using variable in API route


I have an API route, and it works:

import { query as q } from 'faunadb';
    
export default async (req, res) => {
    try {
        const customer = await guestClient
            .query(q.Get(q.Match(q.Index('user_by_username'), "feronimo")))
            .catch((err) => console.error('Error: %s', err));
    
        res.status(200).json(customer.data);
        console.log(customer.data + 'cd');
        console.log(customer + 'c');
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
};

My username is "feronimo" and it comes when I type. However, I have to take this as a variable. I am sending the variable with useSWR:

const fetcher = (params) => (url) => post(url, params);
    
const { data: info, error } = useSWR(
    `/api/profilepages`,
    fetcher({ key: username }) /* {
        dedupingInterval: 1000000
    } */
);

It's returning { username: 'feronimof' }.

export default async (req, res) => {
    const username = req.body;

    const u = username.username;
    try {
        const customer = await guestClient
            .query(q.Get(q.Match(q.Index('user_by_username'), u)))
            .catch((err) => console.error('Error: %s', err));

        res.status(200).json(customer.data);
        console.log(customer.data + 'cd');
        console.log(customer + 'c');
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
};

This returns [object Object].


Solution

  • You could use a dynamic API route in that case, e.g., pages/api/profilepages/[username].js. This allows you to pass a variable when making a request against it.

    // In your component code that makes the request
    
    const { data: info, error } = useSWR(
        `/api/profilepages/${username}`,
        fetcher()
    );
    
    // pages/api/profilepages/[username].js
    
    export default async (req, res) => {
      const u = req.query.username; // This would return the username you sent
    
      // Your API logic here
    };