reactjsreact-hookssolid

React Hook error when loading Solid webId profile


I'm trying to use Solid's react-components to load a user's profile from their webId. I'm running into a problem with useLDflex(). There problem seems to be something to do with React Hooks, but I can't figure it out. My goal is to load the user's profile when the page loads; open to making whatever changes necessary. I'm using MobX for state.

Below is the code and below below is the error in the compiler/web browser. Thank you.

Code (React/JSX/TypeScript):

    import React from 'react';    // 16.14.0
    import { observer } from 'mobx-react';
    import { observable } from 'mobx';
    import { useLDflex } from '@solid/react';    // 1.10.0

    @observer
    export class Profile extends React.Component<{profileId: string}, {}> {
        @observable webId = `https://${this.props.profileId}.solidcommunity.net/profile/card#me`;
        @observable name = useLDflex(`[${this.webId}`)[0];

        render() {
            return (
                <main role="Profile">
                    <div className="container">
                        webId: https://{this.props.profileId}.solidcommunity.net/profile/card#me
                        Name: {this.name}
                    </div>
                </main>
            )
        }
    }

Error:

src/components/profile/index.tsx
  Line 9:24:  React Hook "useLDflex" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

Solution

  • You cannot use React Hooks inside class component, ref here: https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

    So you need to rewrite it to functional component with Mobx, or make a higher order component and pass the props into your class component (when your class is too complex to rewrite)

    import {observer} from "mobx-react";
    
    const Profile = observer(({ profileId }) => {
      // ...
      const name = useLDflex(`...`);
      // ...
    })
    
    const withName = (Component) => ({ profileId }) => {
      const name = useLDflex('...');
      return <Component name={name} profileId={profileId} />
    }
    export default withName(Profile);