Getting error while creating code for my netflix-clone - javascript

Row.js component code where i am calling the api key
Row.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function Row({title, fetchUrl})
{
const [movies, setMovies] = useState([])
// A snippet of code that runs based on a specific condition
useEffect(() => {
//if [], run once when the row load
async function fetchData() {
const request = await axios.get(fetchUrl);
console.log(request);
}
fetchData();
}, []);
return (
<div>
<h2>{title}</h2>
</div>
)
}
axios.js
import axios from "axios";
// base url to make requests to the movie database
const instance = axios.create({
baseURL: "https://api.themoviedb.org/3",
});
export default instance;
Error in the console log is below one, I got the API key from TMBD Api and it was working fine with postman but here in react it is not working properly.
Uncaught (in promise) AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}code: "ERR_BAD_REQUEST"config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}message: "Request failed with status code 404"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta char…not GET /trending/all/week</pre>\n</body>\n</html>\n', status: 404, statusText: 'Not Found', headers: {…}, config: {…}, …}[[Prototype]]: Error
fetchData # Row.js:13
await in fetchData (async)
(anonymous) # Row.js:14
commitHookEffectListMount # react-dom.development.js:23150
invokePassiveEffectMountInDEV # react-dom.development.js:25154
invokeEffectsInDev # react-dom.development.js:27351
commitDoubleInvokeEffectsInDEV # react-dom.development.js:27330
flushPassiveEffectsImpl # react-dom.development.js:27056
flushPassiveEffects # react-dom.development.js:26984
(anonymous) # react-dom.development.js:26769
workLoop # scheduler.development.js:266
flushWork # scheduler.development.js:239
performWorkUntilDeadline # scheduler.development.js:533

you created an axios instance but you did not use it
import instance from "the path to your axios.js file" //like "./axios"
and in the fetchData
async function fetchData() {
const request = await instance.get(fetchUrl);
console.log(request);
}

Related

how do i get rid of axios error uncaught (in promise)?

I am facing the error that uncaught(in promise) in console, its axios related error, I here pasted the code userSearch.jsx file code, where error showing at the end of function's last bracket ? at the end of function's last bracket, I am getting cross sign, why ? and what's the real error?
import { useState, useContext } from "react";
import GithubContext from "../../context/github/GithubContext";
import AlertContext from "../../context/alert/AlertContext";
import { searchUsers } from "../../context/github/GithubActions";
function UserSearch() {
const [text, setText] = useState('')
const { users, dispatch } = useContext(GithubContext)
const { setAlert } = useContext(AlertContext)
const handleChange = (e) => setText(e.target.value)
const handleSubmit = async (e) => {
e.preventDefault()
if (text === '') {
setAlert('Please enter something', 'error')
} else {
dispatch({ type: 'SET_LOADING' })
const users = await searchUsers(text)
dispatch({ type: 'GET_USERS', payload: users })
setText('')
}
}
return (
<div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
<div>
<form onSubmit={handleSubmit}>
<div className='form-control'>
<div className='relative'>
<input
type='text'
className='w-full pr-40 bg-gray-200 input input-lg text-black'
placeholder='Search'
value={text}
onChange={handleChange}
/>
<button
type='submit'
className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
>
Go
</button>
</div>
</div>
</form>
</div>
{users.length > 0 && (
<div>
<button
onClick={() => dispatch({ type: "CLEAR_USERS" })}
className='btn btn-ghost btn-lg'
>
Clear
</button>
</div>
)}
</div>
);
}
export default UserSearch;
ERROR SHOWING IN CONSOLE
GET https://api.github.com/search/users?q=brad 401
dispatchXhrRequest # xhr.js:220
xhrAdapter # xhr.js:16
dispatchRequest # dispatchRequest.js:58
request # Axios.js:109
Axios.<computed> # Axios.js:131
wrap # bind.js:9
searchUsers # GithubActions.js:16
handleSubmit # UserSearch.jsx:21
callCallback # react-dom.development.js:4164
invokeGuardedCallbackDev # react-dom.development.js:4213
invokeGuardedCallback # react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
executeDispatch # react-dom.development.js:9041
processDispatchQueueItemsInOrder # react-dom.development.js:9073
processDispatchQueue # react-dom.development.js:9086
dispatchEventsForPlugins # react-dom.development.js:9097
(anonymous) # react-dom.development.js:9288
batchedUpdates$1 # react-dom.development.js:26140
batchedUpdates # react-dom.development.js:3991
dispatchEventForPluginEventSystem # react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
dispatchEvent # react-dom.development.js:6457
dispatchDiscreteEvent # react-dom.development.js:6430
UserSearch.jsx:26 //ITS ERROR SHOWING BY THE END OF FUCNTION'S LAST BRACKET, ITS SHOWING CROSS SIGN ERROR AT THE END OF OF BRACKET
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
handleSubmit # UserSearch.jsx:26
await in handleSubmit (async)
callCallback # react-dom.development.js:4164
invokeGuardedCallbackDev # react-dom.development.js:4213
invokeGuardedCallback # react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
executeDispatch # react-dom.development.js:9041
processDispatchQueueItemsInOrder # react-dom.development.js:9073
processDispatchQueue # react-dom.development.js:9086
dispatchEventsForPlugins # react-dom.development.js:9097
(anonymous) # react-dom.development.js:9288
batchedUpdates$1 # react-dom.development.js:26140
batchedUpdates # react-dom.development.js:3991
dispatchEventForPluginEventSystem # react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
dispatchEvent # react-dom.development.js:6457
dispatchDiscreteEvent # react-dom.development.js:6430
GithubAction.js file where axios is added
import axios from 'axios'
const GITHUB_URL = process.env.REACT_APP_GITHUB_URL
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN
const github = axios.create({
baseURL: GITHUB_URL,
headers: { Authorization: `token ${GITHUB_TOKEN}` },
})
// Get search results
export const searchUsers = async (text) => {
const params = new URLSearchParams({
q: text,
})
const response = await github.get(`/search/users?${params}`)
return response.data.items
}
// Get user and repos
export const getUserAndRepos = async (login) => {
const [user, repos] = await Promise.all([
github.get(`/users/${login}`),
github.get(`/users/${login}/repos`),
])
return { user: user.data, repos: repos.data }
}
The first line of your Error console GET https://api.github.com/search/users?q=brad 401 has the error code 401, which indicates the user is unauthorized, hence GitHub is rejecting your API request. Probably the token is incorrect or expired.
The second error related to Axios,
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
This happens because the API call to GitHub fails with a 401 error code and you have not implemented any error handling mechanism in your code to properly catch the errors and process them.
In UserSearch.jsx modify the handleSubmit function to use try-catch block
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (text === "") {
setAlert("Please enter something", "error");
} else {
dispatch({ type: "SET_LOADING" });
const users = await searchUsers(text);
dispatch({ type: "GET_USERS", payload: users });
setText("");
}
} catch (error) {
console.log(error.response.data.error)
}
}
This happens because the API call to GitHub fails with a 401 error
code and you have not implemented any error handling mechanism in your
code to properly catch the errors and process theme.
I was facing same issue when I read this answer and I went back to check my code to realize that, while I was returning a value in
doSomething
.catch(error) { reject(false) }
I wasn't receiving it in the caller function's catch block as such
doSomethingCaller
.catch(error) { }
Once you write some error handling code, it stops displaying the error.

Error trying to login on Azure: BrowserAuthError

I'm getting an error trying to login with Azure + TypeScript/JavaScript. The problem is when the user logs in and needs to get redirected to another page. When the response from login is OK, the page remains blank and I need to refresh manually.
This is my config file:
import { Configuration, LogLevel } from "#azure/msal-browser"
export const msalConfig:Configuration = {
auth: {
clientId: process.env.AZURE_CLIENT_LOGIN || "",
authority: "https://login.microsoftonline.com/" + process.env.AZURE_AUTH_LOGIN,
redirectUri: "/admin/dashboard"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level: any, message: any, containsPii: any) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
}
export const loginRequest = {
scopes: ["User.Read"]
};
export const graphConfig = {
graphMeEndpoint: "Enter_the_Graph_Endpoint_Herev1.0/me"
};
And this is my index page:
import React, { useEffect } from 'react';
import type { NextPage } from "next";
import { useRouter } from 'next/router';
import { useMsal } from '#azure/msal-react';
import { useIsAuthenticated } from '#azure/msal-react';
import { loginRequest } from '../services/azureLoginApi';
const Home: NextPage = () => {
const router = useRouter()
const { instance } = useMsal()
const isAuthenticated = useIsAuthenticated()
const redirectToAzureLogin = () => {
instance.loginRedirect(loginRequest).catch((e:any) => {
console.log(e);
});
}
const redirectToDashboard = () => {
router.push('/admin/dashboard')
}
useEffect(()=>{
if(isAuthenticated)
redirectToDashboard()
else
redirectToAzureLogin()
},[])
return (
<div className="index">
</div>
);
};
export default Home;
On console, I get this message:
BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. For more visit: aka.ms/msaljs/browser-errors.
at BrowserAuthError.AuthError [as constructor] (AuthError.js?d98c:27:1)
at new BrowserAuthError (BrowserAuthError.js?be02:197:1)
at Function.BrowserAuthError.createInteractionInProgressError (BrowserAuthError.js?be02:264:1)
at BrowserCacheManager.setInteractionInProgress (BrowserCacheManager.js?6011:886:23)
at PublicClientApplication.ClientApplication.preflightInteractiveRequest (ClientApplication.js?9c57:777:1)
at PublicClientApplication.ClientApplication.preflightBrowserEnvironmentCheck (ClientApplication.js?9c57:762:1)
at PublicClientApplication.eval (ClientApplication.js?9c57:220:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.ClientApplication.acquireTokenRedirect (ClientApplication.js?9c57:214:25)
at PublicClientApplication.eval (PublicClientApplication.js?1b7b:63:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.loginRedirect (PublicClientApplication.js?1b7b:58:25)
at redirectToAzureLogin (index.tsx?db76:18:14)
at eval (index.tsx?db76:31:7)
at invokePassiveEffectCreate (react-dom.development.js?61bb:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994:1)
at invokeGuardedCallback (react-dom.development.js?61bb:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js?61bb:23574:1)
at unstable_runWithPriority (scheduler.development.js?3069:468:1)
at runWithPriority$1 (react-dom.development.js?61bb:11276:1)
at flushPassiveEffects (react-dom.development.js?61bb:23447:1)
at eval (react-dom.development.js?61bb:23324:1)
at workLoop (scheduler.development.js?3069:417:1)
at flushWork (scheduler.development.js?3069:390:1)
at MessagePort.performWorkUntilDeadline (scheduler.development.js?3069:157:1)
The page remains blank until I give a manual refresh on it. With the manual refresh, the redirect works, but without it the page remains freezed.
I've tried some solutions on StackOverflow and other blogs but didn't work out.
Thank you all for any help you may give!
change instance.loginRirect to instance.loignPopup, that would solve that
Problem solved: the point was the useEffect without dependencies. Adding it solved the problem, now the redirect works without needing to manually update the page.

Unhandled Runtime Error: Failed to load script: /_next/static/chunks/pages/api/twitter/generate-auth-link.js

I have a Link tag that looks like <Link href='/api/twitter/generate-auth-link'>Login with Twitter</Link>.
I have already created pages/api/twitter/generate-auth-link.ts that looks like:
import { NextApiResponse } from 'next'
import TwitterApi from 'twitter-api-v2'
import { TWITTER_CONFIG } from '../../../lib/config'
import { SERVER_URL } from '../../../utils/index'
import { NextIronRequest } from '../../../types/index'
import handler from '../../../server/api-route'
const generateAuthLink = async (
req: NextIronRequest,
res: NextApiResponse
) => {
// Generate an authentication URL
const { url, oauth_token, oauth_token_secret } = await new TwitterApi({
appKey: TWITTER_CONFIG.consumerKey,
appSecret: TWITTER_CONFIG.consumerSecret,
}).generateAuthLink(`${SERVER_URL}api/twitter/get-verifier-token`, {linkMode:'authorize'})
req.session.set(oauth_token, oauth_token_secret)
await req.session.save()
// redirect to the authentication URL
res.redirect(url)
}
export default handler().get(generateAuthLink)
When I click on it, it throws the following error:
1 of 1 unhandled error
Unhandled Runtime Error
Error: Failed to load script: /_next/static/chunks/pages/api/twitter/generate-auth-link.js
Call Stack
HTMLScriptElement.script.onerror
node_modules/next/dist/client/route-loader.js (83:51)
How do I fix it?
Reproduction → https://github.com/deadcoder0904/twitter-api-v2-3-legged-login-using-next-connect

Amplify AppSync Subscription Uncaught (in promise)

I am trying to use AWS amplify GraphQL subscription like below,
import Amplify,{ API, Storage, graphqlOperation } from "aws-amplify";
import awsmobile from "../../aws-exports";
Amplify.configure(awsmobile);
...
const notiSubscription = API.graphql(graphqlOperation(onCreateNotification)).subscribe({
next: (todoData) => {
console.log(todoData);
},
});
...
onCreateNotification Graphql is,
subscription OnCreateNotification {
onCreateNotification {
id
}}
Below is the error I get,
AWSAppSyncProvider.ts:204 Uncaught (in promise) undefined
rejected # AWSAppSyncProvider.ts:204
Promise.then (async)
step # AWSAppSyncProvider.ts:204
(anonymous) # AWSAppSyncProvider.ts:204
push../node_modules/#aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter # AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._startSubscriptionWithAWSAppSyncRealTime # AWSAppSyncRealTimeProvider.ts:227
(anonymous) # AWSAppSyncRealTimeProvider.ts:185
Subscription # Observable.js:197
subscribe # Observable.js:279
(anonymous) # PubSub.ts:171
...
Please help me out in this, also my config is
"aws_project_region": "us-east-1",
"aws_appsync_graphqlEndpoint": "https://xxx.appsync-api.us-east-1.amazonaws.com/graphql",
"aws_appsync_region": "us-east-1",
"aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
"aws_appsync_apiKey": "xxxx",
You need to intialize the subscription in a useEffect() hook and then unsubscribe from the subscription.
useEffect(() => {
const subscription = API.graphql(graphqlOperation(onCreateNotification))
.subscribe({
next: todoData => {
console.log(todoData);
}
})
return () => subscription.unsubscribe()
}, [])

i tried an API request but it is giving me this error Uncaught SyntaxError: Unexpected token '<'

i tried fetching an api request from https://suggestqueries.google.com/complete/search? but it is getting back this error "Uncaught SyntaxError: Unexpected token '<'". here is my code
import React, { useState } from 'react';
import suggestSearch from "../../Apis/suggestSearch";
const getSuggestions = () => {
const [autoSearchData, setAutoSearch] = useState("");
const getAutocomplete = async () => {
const response = await suggestSearch.get("", {
params: {
q: searchQuery,
}
});
setAutoSearch(response.data[1]);
console.log(setAutoSearch);
console.log(autoSearchData);
};
}
here is the suggestSearch code
import axios from "axios";
import jsonpAdapter from "axios-jsonp";
export default axios.create({
baseURL: "https://suggestqueries.google.com/complete/search?",
adapter: jsonpAdapter,
params: {
hl: "en", // Language
ds: "yt", // Restrict lookup to youtube
client: "youtube" // force youtube style response, i.e. jsonp
}
});
This error happens because you are referring to an asset that no longer exists. Check your API request link to see if it is still a valid asset.
From the baseURL I'm inferring that you're trying to do a application/x-www-form-urlencoded request.
For such a request to succeed in axios, you will have to import the querystring module and then do axios.post(baseURL,qs.stringify({data}),config). In this case, const qs=require('querystring');.

Categories

Resources