vercel / swr

React Hooks for Data Fetching
https://swr.vercel.app
MIT License
30.14k stars 1.21k forks source link

Module federation: useSWR is not a function #2698

Open danielt69 opened 1 year ago

danielt69 commented 1 year ago

Bug report

Description / Observed Behavior

I get useSWR is not a function every time I use const { trigger, data, error } = useSWRMutation('email-step', apiPost)

Expected Behavior

to work as expected in the docs - return me those values: { trigger, data, error }

Repro Steps / Code Example

Screenshot 2023-06-28 at 17 38 09

import React from 'react';
import useSWRMutation from 'swr/mutation';

const sharedFetch = async (url, options, method) => {
    return fetch(url, {
        ...options,
        method,
        headers: {
            'Content-Type': 'application/json',
            ...options.headers,
        },
        body: JSON.stringify(options.body),
    }).then((res) => res.json());
};

export const apiPost = function (url, options) {
    return sharedFetch(url, options, 'POST');
};

const App = ({ onSubmit = () => {} }) => {

    const { trigger, data, error } = useSWRMutation('email-step', apiPost);

    const handleSubmit = async () => {
        try {
            const result = await trigger(
                { email: "email@gmail.com", eventData: { eventName: 'emailUpdate' } } /* options */,
            );
            // eslint-disable-next-line no-console
            console.log({ result, data, error });
        } catch (e) {
            // eslint-disable-next-line no-console
            console.error(e);
        }
        onSubmit();
    };

    return (
        <button onClick={handleSubmit}
        >
            submit
        </button>
    );
};

export default App;

Additional Context

SWR version: "2.2.0" I used a custom webpack config. Nodejs version 14.15.0

promer94 commented 1 year ago

Could you provide more information here. What bundler did you use here ? Is it a nexjs, vite or react-native project ?

PieterDePauw commented 1 year ago

You should probably use an asynchronous fetcher (apiPost). However, I feel as if you have made multiple 'weird' design choices in this example.

danielt69 commented 1 year ago

It is an asynchronous fetcher. What do you mean by "weird design choices"?

PieterDePauw commented 1 year ago

It is an asynchronous fetcher. What do you mean by "weird design choices"?

Well, of course, I am not really sure what you intended exactly. I guess that you should just not resolve the fetch API with json, but it would be easier to determine the problem if you could provide some more information as promer94 has previously suggested.

danielt69 commented 1 year ago

I also use Module Federation if it makes any difference.

PieterDePauw commented 1 year ago

I also use Module Federation if it makes any difference.

Could you provide a (minimal) reproduction of the problem in something like codesandbox?

promer94 commented 1 year ago

https://github.com/webpack/webpack/issues/16125

It's webpack's issue. I am sorry but i don't know any workaround for this

devjiwonchoi commented 1 year ago

@danielt69 https://github.com/webpack/webpack/issues/16125#issuecomment-1210447191 This seems like a workaround, give it a try.

danielt69 commented 1 year ago

Eventually, I managed to workaround it by adding the following settings to the Webpack config:

const path = require('path');
const packageJson = require(path.join(process.cwd(), 'package.json'));
const deps = packageJson.dependencies;

const excludePackages = ['swr'];

const shared = Object.keys(deps).reduce((acc, curr) => {
    if (excludePackages.find((o) => o === curr)) {
        return { ...acc };
    } else {
        return {
            [curr]: deps[curr],
            ...acc,
        };
    }
}, {});

module.exports = {
    name: 'ModuleBoilerplate',
    exposes: {
        index: path.join(process.cwd(), 'src/index.js'),
    },
    shared,
};
koba04 commented 6 months ago

Could you try it again with v2.2.5?

VugarAhmadov commented 1 month ago

Could you try it again with v2.2.5?

Tested on ModuleFederation with swr version of 2.2.5. It is working.