uppload
uppload copied to clipboard
Unable to call uppload with dynamic method using nextjs
Describe the bug I am using latest uppload and trying to integrate it with nextjs. here is what i get when i call uppload:
Unhandled Runtime Error
TypeError: Uppload.on is not a function
To Reproduce Steps to reproduce the behavior: You can see my implementation on stackblitz.com-nextjs-fwhaef Basically, here how i try it:
components/uppload.js
import { Uppload, en, Local, fetchUploader } from 'uppload';
const uppload = new Uppload({
lang: en,
defaultService: 'local',
maxSize: [1024, 1024],
uploader: fetchUploader({
endpoint: 'https://your-backend.com/upload'
})
});
uppload.use([new Local()]);
export default uppload;
index.js
import Head from 'next/head';
import dynamic from 'next/dynamic';
import { useEffect, useState } from 'react';
import styles from '../styles/Home.module.css';
const Uppload = dynamic(() => import('../components/uppload'), {
ssr: false
});
const URL = 'https://cdn.stocksnap.io/img-thumbs/280h/TLCYRTMCTR.jpg';
export default function Home() {
const [image, setImage] = useState(URL);
useEffect(() => {
Uppload.on('upload', url => {
setImage(url);
});
});
const doUpload = async evt => {
evt.preventDefault();
Uppload.open();
};
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
</Head>
<main className={styles.main}>
<h1 className={styles.title}>Test uppload</h1>
<a
className="uppload-button"
href="/#upload"
onClick={evt => doUpload(evt)}
>
click to upload
</a>
</main>
<footer className={styles.footer}>
<p>Power by Uppload</p>
</footer>
</div>
);
}
Expected behavior I try with reactjs, it working ok, but nextjs give me an error like above.
next/dynamic only works with React components.
https://nextjs.org/docs/advanced-features/dynamic-import
How to fix this issue for next.js
?
@hedaukartik Just dynamic import the component in which you call uppload
const Uppload = dynamic(() => import("./uppload/uppload_new_file"), {
loading: () => <p>Loading...</p>,
ssr: false,
});
Then, in your uppload_new_file.tsx:
import { uppload } from "./index";
export default function UpploadNewFile() {
const manageUpploadResult = (res) => {
const { dataFile } = res;
console.log(dataFile.name);
};
const open = () => {
uppload.on("upload", (res) => {
manageUpploadResult(res);
});
uppload.open();
};
return (
<button onClick={open}>
<p>[Add an image]</p>
</button>
);
}
And finally, in your index.tsx:
import {
Uppload,
} from "uppload";
export const uppload = new Uppload({
etc.
})