Spotify OAuth с React не работает должным образомJavascript

Форум по Javascript
Ответить
Гость
 Spotify OAuth с React не работает должным образом

Сообщение Гость »

Я вообще новичок в React и пытаюсь создать простое приложение. Я хочу создать приложение, в котором пользователи смогут входить в систему, используя свою учетную запись Spotify. У меня есть следующие файлы: :

Код: Выделить всё

import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import './App.css';
import OAuthSignInPage from './components/oauth';
import Callback from './components/callback';
import Welcome from './components/Welcome';
import Options from './components/Options';
import Header from './components/Header';
import { AuthProvider, useAuth } from './hooks/useAuth';

const ProtectedRoute = ({ children }) => {
const { user } = useAuth();
if (!user) {
return ;
}
return children;
};

function App() {
return (















);
}

export default App;

Код: Выделить всё

oauth.js

Код: Выделить всё

import * as React from 'react';
import { AppProvider } from '@toolpad/core/AppProvider';
import { SignInPage } from '@toolpad/core/SignInPage';
import { useTheme } from '@mui/material/styles';
import { useAuth } from "../hooks/useAuth";
import { useNavigate } from 'react-router-dom';

const providers = [
{ id: 'spotify', name: 'Spotify' }
];

const signIn = async (provider) => {

if (provider.id === 'spotify') {
// Redirect to Spotify login
const clientId = process.env.REACT_APP_SPOTIFY_CLIENT_ID;
const redirectUri = encodeURIComponent(`${window.location.origin}/callback`);
const scope = 'user-read-private user-read-email user-top-read';
const spotifyAuthUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=code&redirect_uri=${redirectUri}&scope=${scope}`;

window.location.href = spotifyAuthUrl;
return new Promise(() => {}); // Promise won't resolve due to redirect
}

return { error: 'Invalid provider' };
};

export default function OAuthSignInPage() {
const { user } = useAuth();
const navigate = useNavigate();

React.useEffect(() => {
if (user) {
navigate('/options');
}
}, [user, navigate]);

const theme = useTheme();
return (



);
}

Код: Выделить всё

protectedRoute.js
:

Код: Выделить всё

import { Navigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";

export const ProtectedRoute = ({ children }) => {
const { user } = useAuth();
if (!user) {
// user is not authenticated
return ;
}
return children;
};

Код: Выделить всё

Callback.js

Код: Выделить всё

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

function Callback() {
const { login } = useAuth();
const location = useLocation();

useEffect(() =>  {
const code = new URLSearchParams(location.search).get('code');
if (code) {
login({ code });
}
}, [location, login]);

// No need for loading state since login handles navigation
return null;
}

export default Callback;

Код: Выделить всё

useAuth.jsx

Код: Выделить всё

import { createContext, useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useLocalStorage } from "./useLocalStorage";
const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [user, setUser] = useLocalStorage("code", null);
const navigate = useNavigate();

// call this function when you want to authenticate the user
const login = async (data) => {
setUser(data);
};

// call this function to sign out logged in user
const logout = () => {
setUser(null);
navigate("/", { replace: true });
};

const value = useMemo(
() => ({
user,
login,
logout,
}),
[user]
);
return {children};
};

export const useAuth = () => {
return useContext(AuthContext);
};
Проблема в том, что часть OAuth работает нормально. Я могу войти в систему, и Spotify вызывает мою конечную точку /callback с кодом. Но перенаправление работает неправильно. После входа в систему он переходит по маршруту /options, но это пустой компонент. Ошибка:

Код: Выделить всё

Cannot update a component (`AuthProvider`) while rendering a different component (`Callback`). To locate the bad setState() call inside `Callback`, follow the stack trace as described in https://react.dev/link/setstate-in-render
И эта ошибка вызывается в бесконечном цикле.
Я просто не могу понять, как это решить. Еще одна вещь: когда я вручную ввожу URL-адрес /welcome после входа в систему, это работает. Помощь будет очень признательна.

Подробнее здесь: https://stackoverflow.com/questions/793 ... g-properly
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»