React InertiaJS Laravel (Uncaught (in promise) TypeError: this.resolveComponent is not a function)

54 views Asked by At

I have project on stack: React, vite, typescript, laravel, InertiaJs. it is my app.tsx

import "./bootstrap";
import "../css/app.css";
import { createRoot } from "react-dom/client";
import { createInertiaApp } from "@inertiajs/react";
import { InertiaProgress } from "@inertiajs/progress";

const appName =
    window.document.getElementsByTagName("title")[0]?.innerText || "Laravel";

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) =>
        import(`./Pages/${name}`).then((module) => module.default),
    setup({ el, App, props }) {
        const root = createRoot(el); // создаем корень с помощью createRoot
        root.render(<App {...props} />);
    },
});

InertiaProgress.init({ color: "#4B5563" });

it's my login component:

import React, { useState } from "react";
import { InertiaLink } from "@inertiajs/inertia-react";
import { Inertia } from "@inertiajs/inertia";
import styles from "../../css/login.module.css";
import Label from "../Components/Label";
import logo from "../../../public/icons/logo.svg";
import vk from "../../../public/icons/vk.svg";
import anime from "../../../public/images/anime.jpg";
import { FaTelegramPlane } from "react-icons/fa";
import CustomCheckbox from "../Components/CustomCheckbox";
import Button from "../Components/Button";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm as useReactHookForm } from "react-hook-form";
import { toast } from "react-toastify";

const schema = Yup.object().shape({
    email: Yup.string()
        .email("Пожалуйста, введите корректный Email")
        .required("Пожалуйста, введите Email"),
    password: Yup.string().required("Пожалуйста, введите пароль"),
});

type DataType = {
    email: string;
    password: string;
};
const Login: React.FC = () => {
    const [check, setCheck] = useState(false);
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useReactHookForm({
        resolver: yupResolver(schema),
    });
    const onSubmit = (data: DataType) => {
        Inertia.post(
            "/login",
            {
                ...data,
                remember_me: check ? 1 : 0,
            },
            {
                onError: (err) => {
                    console.log(err);
                    toast.error("Что-то пошло не так");
                },
                onSuccess: (event: any) => {
                    toast.success("Успешный вход");
                },
            }
        );
    };

    return (
        <div className={styles.login}>
            <div className={styles.loginLeft}>
                <div className={styles.logo}>
                    <InertiaLink href="/">
                        <img src={logo} alt="logo" />
                    </InertiaLink>
                    <h3>Wallone</h3>
                    <h4>#Визуальная новелла</h4>
                </div>
                <div className={styles.socials}>
                    <InertiaLink href="#">
                        <img src={vk} alt="vk" />
                    </InertiaLink>
                    <InertiaLink href="#">
                        <FaTelegramPlane />
                    </InertiaLink>
                </div>
                <img src={anime} alt="anime" />
            </div>
            <div className={styles.loginRight}>
                <div className={styles.loginForm}>
                    <div className={styles.navigation}>
                        <InertiaLink
                            href="/login"
                            className={styles.activeNavigation}
                        >
                            Авторизация
                        </InertiaLink>
                        <InertiaLink href="/register">Регистрация</InertiaLink>
                    </div>
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <Label
                            title="Email"
                            placeholder="Введите ваш Email..."
                            type="email"
                            name="email"
                            register={register("email")}
                            errorMsg={errors.email?.message}
                        />
                        <Label
                            title="Пароль"
                            placeholder="Введите ваш пароль..."
                            type="password"
                            name="password"
                            register={register("password")}
                            errorMsg={errors.password?.message}
                        />
                        <CustomCheckbox
                            checked={check}
                            onChange={() => setCheck(!check)}
                            text="Запомнить меня"
                        />
                        <div className={styles.actions}>
                            <Button text="Войти" />
                            <InertiaLink href="/reset">
                                Забыли пароль?
                            </InertiaLink>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default Login;

it's my Header component:

import React, { useState, useRef } from "react";
import styles from "../../css/header.module.css";
import logo from "../../../public/icons/logo.svg";
import user from "../../../public/icons/user.svg";
import Search from "../Components/Search";
import { IoIosArrowDown } from "react-icons/io";
import { HiLogin } from "react-icons/hi";
import { AnimatePresence, motion } from "framer-motion";
import { useClickOutSide } from "../../hooks/useClickOutSide";
import { InertiaLink } from "@inertiajs/inertia-react";
const Header: React.FC = () => {
    const [drop, setDrop] = useState(false);
    const dropRef = useRef(null);
    useClickOutSide(dropRef, () => {
        setDrop(false);
    });
    return (
        <div className={styles.header}>
            <div className={styles.logo}>
                <InertiaLink href="/">
                    <img src={logo} alt="" />
                </InertiaLink>
                <div className={styles.morePopular}>
                    <h2>Wallone</h2>
                    <h4>#Бесконечн...</h4>
                </div>
            </div>
            <Search />
            <div className={styles.language}>
                <h3>RU</h3>
                <span>|</span>
                <h3>EN</h3>
            </div>
            <div
                className={styles.account}
                data-value="account"
                onClick={() => setDrop((drop) => !drop)}
            >
                <img src={user} alt="" />
                <h4>Sergey Eg...</h4>
                <IoIosArrowDown />
                {drop && (
                    <AnimatePresence>
                        <motion.ul
                            initial={{ y: -100 }}
                            animate={{ y: 0 }}
                            exit={{ y: -100 }}
                            ref={dropRef}
                            data-value="accDropdown"
                            className={styles.accDropdown}
                            onClick={(e) => e.stopPropagation()}
                        >
                            <InertiaLink
                                href="/register"
                                onClick={(e) => {
                                    e.preventDefault();
                                    setDrop(false);
                                }}
                            >
                                <HiLogin />
                                <h3>Регистрация</h3>
                            </InertiaLink>
                            <InertiaLink
                                href="/login"
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setDrop(false);
                                }}
                            >
                                <HiLogin />
                                <h3>Авторизация</h3>
                            </InertiaLink>
                        </motion.ul>
                    </AnimatePresence>
                )}
            </div>
        </div>
    );
};

export default Header;

I have two problems. The first is when I click on the login in the header and go to the login page (or another page) my browser tab is completely refreshed. but this should not happen in a react application)

The second and main problem is that at the beginning there are no errors in my console. When sending a request for authorization on the login page, I get an error: Uncaught (in promise) TypeError: this.resolveComponent is not a function. I never had this error before. Here is the processing of this path on the server side:

Route::post('login', [AuthController::class, 'login']); 
Route::get('/login', function () {
    return Inertia::render('Login', [
        'title' => "Login",
    ]);
});

it's my AuthController:

    public function login(LoginRequest $request)
    {
        try {
            $credentials = $request->only('email', 'password');
            $remember = $request->boolean('remember_me');

            if (Auth::attempt($credentials, $remember)) {
                $user = User::where('email', $request->email)->first();

                // JWT token oluştur
                $token = $user->createToken('API Token')->plainTextToken;

                return Inertia::render('Login',[
                    'message' => __("SuccessfullyLogin"),
                    'data' => ['token' => $token],
                ]);
            } else {
                return Inertia::render('Login',[
                    'error' => __("InvalidCredentials"),
                ]);
            }
        } catch (\Exception $e) {
            return Inertia::render('Login',[
                'error' => __("An error occurred while processing the request"),
                'details' => $e->getMessage(),
            ]);
        }
    }

please help me for this questions.

I try everythink but it not help for resolve this problem

else i want add other files. it's my tsconfig:

{
    "compilerOptions": {
        "target": "esnext", // Указывает целевую версию ECMAScript для компиляции
        "module": "esnext", // Разрешает использование import.meta
        "jsx": "react-jsx", // Указывает режим обработки JSX
        "esModuleInterop": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "skipLibCheck": true
    },
    "include": ["resources/js/**/*", "react-app-env.d.ts"]
}

it's my viteconfig:

import { defineConfig } from "vite";
import laravel from "laravel-vite-plugin";
import react from "@vitejs/plugin-react";

export default defineConfig({
    plugins: [
        laravel({
            input: "resources/js/app.tsx",
            refresh: true,
        }),
        react(),
    ],
});

I update all packages but it's not help.

0

There are 0 answers