Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Something went wrong while processing your request. while running a minimal demo #16

Closed
imWildCat opened this issue Jul 23, 2022 · 11 comments

Comments

@imWildCat
Copy link

  • Client version: "pocketbase": "^0.2.1",
  • Server version:
    pocketbase version 0.3.2
  • Client code:
    • vite
function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    PocketBaseClient.getFeedbacks().then(feedbacks => {
      console.log(feedbacks);
    }).catch(err => {
      console.log(err);
    });
  });

import PocketBase, { Record } from "pocketbase";

const client = new PocketBase(process.env.NODE_ENV === "production" ? process.env.PB_URL : "http://localhost:8090");

export class PocketBaseClient {
  static getFeedbacks = async (): Promise<Record[]> => {
    const records = await client.Records.getFullList("feedback", 200 /* batch size */, {
      sort: "-created",
    });

    return records;
  }
}

package.json:

{
  "name": "web",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "pocketbase": "^0.2.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.15",
    "@types/react-dom": "^18.0.6",
    "@vitejs/plugin-react": "^2.0.0",
    "typescript": "^4.6.4",
    "vite": "^3.0.0"
  }
}

Error stack:

ClientResponseError 0: Something went wrong while processing your request.
    at new i2 (ClientResponseError.ts:13:9)
    at Client.ts:175:23
    at async PocketBaseClient.getFeedbacks (index.ts:7:21)

The JSON response looks good:

{
  "page": 1,
  "perPage": 200,
  "totalItems": 1,
  "items": [
    {
      "@collectionId": "icxcxKTTpbM7iv9",
      "@collectionName": "feedback",
      "attachments": [
        "DsOmZWHtfBnCFAcXSQsn1RmswOykjuR0.png"
      ],
      "created": "2022-07-23 13:08:35.599",
      "email": "[email protected]",
      "id": "rJJTW8mAXt6uoDk",
      "metadata": {
        "foo": 1
      },
      "updated": "2022-07-23 13:08:35.599"
    }
  ]
}

Now sure why there's such an error ?

@ganigeorgiev
Copy link
Member

It is possible to receive a ClientResponseError due to the auto cancellation of pending duplicated requests. This could happen if for example the effect is triggered multiple times before the previous request complete.

To verify this, you could inspect the error and check if error.isAbort is true.

In the Caveats section there are examples how to disable the auto cancellation behavior if you don't want it.

@imWildCat
Copy link
Author

Thank you very much!

Yeah, it is exactly the reason.

  useEffect(() => {
    PocketBaseClient.getFeedbacks().then(feedbacks => {
      console.log(feedbacks);
    }).catch(err => {
      console.log(err);
      console.log(err.isAbort); // true
    });
  });

@CM-IV
Copy link

CM-IV commented Nov 11, 2022

Should probably make another issue for this, but here goes:

Software Stack:

  • NextJS 13
  • PocketBase v0.8.0-rc2

Getting a similar error when creating/updating/deleting with v0.8.0-rc2 in Firefox, but not in a Chromium-based browser.

Error:  ClientResponseError 0: Something went wrong while processing your request.
    i pocketbase.es.mjs:1
    send pocketbase.es.mjs:1
    promise callback*E</t.prototype.send/</< pocketbase.es.mjs:1
    a pocketbase.es.mjs:1
    a pocketbase.es.mjs:1
    i pocketbase.es.mjs:1
    i pocketbase.es.mjs:1
    send pocketbase.es.mjs:1
    _delete pocketbase.es.mjs:1
    delete pocketbase.es.mjs:1
    delete pocketbase.es.mjs:1
    delContact deleteContact.tsx:16
    callCallback react-dom.development.js:4246
    invokeGuardedCallbackDev react-dom.development.js:4295
    invokeGuardedCallback react-dom.development.js:4359
    invokeGuardedCallbackAndCatchFirstError react-dom.development.js:4373
    executeDispatch react-dom.development.js:9183
    processDispatchQueueItemsInOrder react-dom.development.js:9215
    processDispatchQueue react-dom.development.js:9228
    dispatchEventsForPlugins react-dom.development.js:9239
    dispatchEventForPluginEventSystem react-dom.development.js:9430
    batchedUpdates$1 react-dom.development.js:30293
    batchedUpdates react-dom.development.js:4069
    dispatchEventForPluginEventSystem react-dom.development.js:9429
    dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay react-dom.development.js:6591
    dispatchEvent react-dom.development.js:6583
    dispatchDiscreteEvent react-dom.development.js:6556
deleteContact.tsx:23:20
false

I am logging error.isAbort and that is false.

Whenever I use Chrome as the browser, I receive no error and CRUD functionality works.

Here is the relevant client-component code:

'use client';

import { useRouter } from 'next/navigation';
import { usePathname } from 'next/navigation';
import { db } from "../(db)/pbInit";

export default function DeleteContact() {

    const router = useRouter();
    const pathname = usePathname();
    const urlId = pathname!.split("/")[2].substring(0, 36);

    async function delContact() {

        try {
            await db.collection("contacts").delete(urlId);
    
            router.back();

            router.refresh();
            
        } catch (error) {
            console.log("Error: ", error);
            /*@ts-ignore*/
            console.log(error.isAbort);
        }
    }

    return (
        <form onSubmit={delContact}>
            <div className="field">
                <p className="control">
                    <button className="button is-danger" type="submit">Delete</button>
                </p>
            </div>
        </form>
    )
}

The above client component is then used inside of a default Server-Rendered page with NextJS 13:

import DeleteContact from "../../(components)/deleteContact";
import Link from "next/link";
import PocketBase from "pocketbase";
import type { Contact } from "../../../types";

export const dynamic = 'auto',
  dynamicParams = true,
  revalidate = 10,
  fetchCache = 'auto',
  runtime = 'nodejs',
  preferredRegion = 'auto'

async function getContact(contactId: string) {
    const db = new PocketBase("http://localhost:8090");

    const data = await db.collection("contacts").getOne<Contact>(contactId);

    return data as Contact;
}


export default async function ContactPage({ params }: any) {
    const contact = await getContact(params.id);
    console.log(contact)

    return (
        <>
            <section className="section section-divider">
                <h1 className="title">{contact.name}'s Contact Page</h1>
                <div className="box">
                    <div className="field">
                        <label className="label">Name</label>
                        <p>{contact.name}</p>
                    </div>
                    <div className="field">
                        <label className="label">Email</label>
                        <p>{contact.email}</p>
                    </div>
                    <div className="field">
                        <label className="label">Date of Birth</label>
                        <p>{contact.date_of_birth}</p>
                    </div>
                    <div className="field">
                        <label className="label">Workplace</label>
                        <p>{contact.workplace}</p>
                    </div>
                    <hr />
                    <nav className="level">
                        <div className="level-left">
                            <div className="level-item">
                                <DeleteContact />
                            </div>
                            <div className="level-item">
                            <Link href={`/contacts/${contact.id}/edit`}>
                                <button className="button is-success">Edit</button>
                            </Link>
                            </div>
                        </div>
                    </nav>
                </div>
            </section>
        </>
    )

}

@ganigeorgiev
Copy link
Member

@CM-IV I'm not sure how to reproduce the error. I haven't got time yet to check nextjs13 and how it workds, but here are some things you could try to debug it:

  • ClientResponseError 0 indicates that this is most likely an abort request (depending on your environment and the node version you are running isAbort could be false if DOMException is not available).

  • If you are using Node 17+, change the localhost:8090 address to 127.0.0.1:8090 due to the different DNS resolution (more info in Node 17+ localhost resolution #21)

  • Start the executable with --debug and/or check for more detailed error logs in the console or in the "Admin UI > Logs"

@ganigeorgiev
Copy link
Member

ganigeorgiev commented Nov 11, 2022

@CM-IV Additionally, to rule out autocancellation error, you can also try to disable it globally using:

// call right after initializing the SDK
db.autoCancellation(false);

@CM-IV
Copy link

CM-IV commented Nov 11, 2022

@ganigeorgiev

Thanks for the response, I'm running Node v18.12.1

I have changed the IP addresses and set autoCancellation to false in the init file that I am exporting the PocketBase instance in:

//Init the database

import PocketBase from 'pocketbase';

export const db = new PocketBase('http://127.0.0.1:8090');
db.autoCancellation(false);

I still receive the same error when Updating/Creating/Deleting a contact inside of FireFox.

Inside the Admin UI logs, I'm only able to see the DELETE/PATCH/CREATE reqs from the chromium browser - I'm not seeing any of those reqs from Firefox.

image

@ganigeorgiev
Copy link
Member

@CM-IV If you are not seeing the error in the Admin UI then that means that the request has never reached the server and has failed due to some client-side error.

You could also try inspecting the returned original error for eventual hints what could be underlying issue - console.log(error.originalError).

If the above doesn't help, could you provide a minimal reproducible repo?

@CM-IV
Copy link

CM-IV commented Nov 11, 2022

Adding console.log(error.originalError) provides this in the browser console along with the ClientResponseError 0 (in FireFox v106.0):

TypeError: NetworkError when attempting to fetch resource.

The repo is on the dev branch here if you'd like to tinker with it: https://github.com/CM-IV/nextjs13-contacts-manager

git clone -b dev https://github.com/CM-IV/nextjs13-contacts-manager.git

I'm using the v0.8.0-rc2 executable in the root dir of the project, so where the package.json is located.

Here is the contacts collection, wherein everyone has access in the API Rules:

[
    {
        "id": "_pb_users_auth_",
        "name": "users",
        "type": "auth",
        "system": false,
        "schema": [
            {
                "id": "users_name",
                "name": "name",
                "type": "text",
                "system": false,
                "required": false,
                "unique": false,
                "options": {
                    "min": null,
                    "max": null,
                    "pattern": ""
                }
            },
            {
                "id": "users_avatar",
                "name": "avatar",
                "type": "file",
                "system": false,
                "required": false,
                "unique": false,
                "options": {
                    "maxSelect": 1,
                    "maxSize": 5242880,
                    "mimeTypes": [
                        "image/jpg",
                        "image/jpeg",
                        "image/png",
                        "image/svg+xml",
                        "image/gif"
                    ],
                    "thumbs": null
                }
            }
        ],
        "listRule": "id = @request.auth.id",
        "viewRule": "id = @request.auth.id",
        "createRule": "",
        "updateRule": "id = @request.auth.id",
        "deleteRule": "id = @request.auth.id",
        "options": {
            "allowEmailAuth": true,
            "allowOAuth2Auth": true,
            "allowUsernameAuth": true,
            "exceptEmailDomains": null,
            "manageRule": null,
            "minPasswordLength": 8,
            "onlyEmailDomains": null,
            "requireEmail": false
        }
    },
    {
        "id": "r9pb8caefgjvthr",
        "name": "contacts",
        "type": "base",
        "system": false,
        "schema": [
            {
                "id": "6okregou",
                "name": "name",
                "type": "text",
                "system": false,
                "required": true,
                "unique": false,
                "options": {
                    "min": null,
                    "max": null,
                    "pattern": ""
                }
            },
            {
                "id": "yk5e9aj8",
                "name": "email",
                "type": "text",
                "system": false,
                "required": true,
                "unique": true,
                "options": {
                    "min": null,
                    "max": null,
                    "pattern": ""
                }
            },
            {
                "id": "9rdgdkce",
                "name": "date_of_birth",
                "type": "text",
                "system": false,
                "required": true,
                "unique": false,
                "options": {
                    "min": null,
                    "max": null,
                    "pattern": ""
                }
            },
            {
                "id": "uctev71d",
                "name": "workplace",
                "type": "text",
                "system": false,
                "required": true,
                "unique": false,
                "options": {
                    "min": null,
                    "max": null,
                    "pattern": ""
                }
            }
        ],
        "listRule": "",
        "viewRule": "",
        "createRule": "",
        "updateRule": "",
        "deleteRule": "",
        "options": {}
    }
]

image

@ganigeorgiev
Copy link
Member

@CM-IV Hm, TypeError: NetworkError when attempting to fetch resource. is usually a CORS error and it is most likely caused because nextjs13 as far as I know uses their own custom fetch. I'll try to find time tomorrow and will test the repo locally to see if I can reproduce it.

@ganigeorgiev
Copy link
Member

@CM-IV I've cloned your repo and it seems that it is not a cors issue (or at least not directly).

Your code currently has a side effect - when you try to submit the edit or delete form, the native form submit event is not stopped/prevented and it is causing page refresh/redirect while the fetch call is being processed. There is an open "issue" in Firefox for that in https://bugzilla.mozilla.org/show_bug.cgi?id=1280189.

To fix it, you need to prevent the native browser form behavior and leave your javascript to handle the form submission, aka. you have to add e.preventDefault() to your onSubmit handlers. Here is for example the delContact:

    async function delContact(e) {
        e.preventDefault();

        try {
            await db.collection("contacts").delete(urlId);
    
            router.back();

            router.refresh();
        } catch (err) {
            /*@ts-ignore*/
            console.log(err.originalError);
        }
    }

@CM-IV
Copy link

CM-IV commented Nov 13, 2022

Thanks for the help, @ganigeorgiev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants