Spotify OAuth mit React funktioniert nicht richtigJavaScript

Javascript-Forum
Guest
 Spotify OAuth mit React funktioniert nicht richtig

Post by Guest »

Ich bin React-Neuling im Allgemeinen und versuche, eine einfache Anwendung zu erstellen. Ich möchte eine Anwendung erstellen, bei der sich Benutzer mit ihrem Spotify-Konto anmelden können. Ich habe die folgenden Dateien:

Code: Select all

App.js
:

Code: Select all

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;

Code: Select all

oauth.js

Code: Select all

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 (



);
}

Code: Select all

protectedRoute.js
:

Code: Select all

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;
};

Code: Select all

Callback.js

Code: Select all

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;

Code: Select all

useAuth.jsx

Code: Select all

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);
};
Das Problem ist nun, dass der OAuth-Teil einwandfrei funktioniert. Ich kann mich anmelden und Spotify ruft meinen /callback-Endpunkt mit dem Code auf. Aber die Umleitung funktioniert nicht richtig. Nach der Anmeldung wird die Route /options aufgerufen, es handelt sich jedoch um eine leere Komponente. Der Fehler ist:

Code: Select all

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
Und dieser Fehler wird in einer Endlosschleife aufgerufen.
Ich weiß einfach nicht, wie ich das lösen kann. Eine weitere Sache ist, dass es funktioniert, wenn ich nach der Anmeldung die URL /welcome manuell eingebe. Hilfe wäre wirklich dankbar.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post