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()
}, [])
Related
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.
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);
}
I am trying to build my own staking page for my NFT project. I cloned a repo named gem-farm from github. But I am facing with an issue when I start it at localhost.
index.js?9d03:45 TypeError: Cannot read properties of undefined (reading 'protocol')
at isURLSameOrigin (isURLSameOrigin.js?3934:57:1)
at dispatchXhrRequest (xhr.js?b50d:145:1)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js?b50d:15:1)
at dispatchRequest (dispatchRequest.js?5270:58:1)
at Axios.request (Axios.js?0a06:108:1)
at Axios.<computed> [as get] (Axios.js?0a06:129:1)
at Function.wrap [as get] (bind.js?1d2b:9:1)
at _callee$ (cluster.ts?b691:26:1)
at c (blocto-sdk.umd.js?758a:3:1)
I think it is caused by this file since it is the only file using axios
Where it imports axios:
import { TOKEN_PROGRAM_ID } from '#solana/spl-token';
import axios from 'axios';
import { programs } from '#metaplex/js';
This is where it uses axios:
async function getNFTMetadata(
mint: string,
conn: Connection,
pubkey?: string
): Promise<INFT | undefined> {
// console.log('Pulling metadata for:', mint);
try {
const metadataPDA = await Metadata.getPDA(mint);
const onchainMetadata = (await Metadata.load(conn, metadataPDA)).data;
const externalMetadata = (await axios.get(onchainMetadata.data.uri)).data;
return {
pubkey: pubkey ? new PublicKey(pubkey) : undefined,
mint: new PublicKey(mint),
onchainMetadata,
externalMetadata,
};
} catch (e) {
console.log(`failed to pull metadata for token ${mint}`);
}
}
I tried it on both PC & Macos. I couldn't find any solution. Thanks.
When I import sqlite3 to try and test my database connection I get an error, when I opened the development tools I found this stating:
Uncaught ReferenceError: require is not defined
at Object.path (external "path":1)
at __webpack_require__ (bootstrap:789)
at fn (bootstrap:100)
at Object../node_modules/sqlite3/lib/sqlite3.js (sqlite3.js:1)
at __webpack_require__ (bootstrap:789)
at fn (bootstrap:100)
at Object.<anonymous> (App.tsx:3)
at Object../src/App.tsx (App.tsx:22)
at __webpack_require__ (bootstrap:789)
at fn (bootstrap:100)
path # external "path":1
__webpack_require__ # bootstrap:789
fn # bootstrap:100
./node_modules/sqlite3/lib/sqlite3.js # sqlite3.js:1
__webpack_require__ # bootstrap:789
fn # bootstrap:100
(anonymous) # App.tsx:3
./src/App.tsx # App.tsx:22
__webpack_require__ # bootstrap:789
fn # bootstrap:100
./src/renderer.tsx # renderer.tsx:4
__webpack_require__ # bootstrap:789
fn # bootstrap:100
0 # renderer.tsx:6
__webpack_require__ # bootstrap:789
(anonymous) # bootstrap:856
(anonymous)
and this is the code I wrote:
import { hot } from "react-hot-loader";
import React, { useEffect } from "react";
import sqlite3 from "sqlite3";
const App = () => {
useEffect(() => {
let db = new sqlite3.Database("./database.sqlite", (err: any) => {
if (err) {
return console.error(err.message);
}
console.log("Connected to database");
});
});
return (
<div>
<h1>Testing</h1>
<h2>sdfsdfs </h2>
</div>
);
};
export default hot(module)(App);
I'm using Electron, React, Typescript
Do not connect sqlite directly with React components. Make the application core separate and connect with the frontend using Electron IPC.
I am trying to create an app which allow the user to upload an image and display it in the page with React and Firebase.
this is the part of the code that responsible for the issue:
the image variable is coming from from the state
const [image, setImage] = useState("");
const [caption, setCaption] = useState("");
const [progress, setProgress] = useState(0)
function handleChange (e){
if (e.target.files[0]){
setImage(e.target.files[0]);
}
}
function handleUpload(){
const uploadTask = storage.ref('images/${image.name}').put(image)
uploadTask.on(
"state_changed",
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
console.log(error);
alert(error.message);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
db.collection("posts").add({
timestamp: db.FieldValue.serverTimestamp(),
caption : caption,
imgUrl: url,
userName: username
})
setProgress(0);
setCaption("");
setImage(null);
})
}
)
}
and this error get logged in the console :
Uncaught
FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}code_: "storage/invalid-argument"message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."name_: "FirebaseError"serverResponse_: nullcode: (...)message: (...)name: (...)serverResponse: (...)__proto__: Object
rethrowCaughtError # react-dom.development.js:328
runEventsInBatch # react-dom.development.js:3336
runExtractedPluginEventsInBatch # react-dom.development.js:3537
handleTopLevel # react-dom.development.js:3581
batchedEventUpdates$1 # react-dom.development.js:21729
batchedEventUpdates # react-dom.development.js:798
dispatchEventForLegacyPluginEventSystem # react-dom.development.js:3591
attemptToDispatchEvent # react-dom.development.js:4311
dispatchEvent # react-dom.development.js:4232
unstable_runWithPriority # scheduler.development.js:659
runWithPriority$1 # react-dom.development.js:11077
discreteUpdates$1 # react-dom.development.js:21746
discreteUpdates # react-dom.development.js:811
dispatchDiscreteEvent # react-dom.development.js:4211
I have tried to change put(image) to put(blob) but it did not work
The line:
const uploadTask = storage.ref('images/${image.name}').put(image)
Has an error, it should be using the symbol ` (backquote/backtick) instead of using single quotes ':
const uploadTask = storage.ref(`images/${image.name}`).put(image)
otherwise you will create a reference to the literal string images/${image.name} instead of image/value_of_variable_image.jpg more about Template literals can be found here
You haven't still showed us what's the content of the image variable, I can see from the code that you're calling a setState inside a function that appears to be a callback, but I'm not seeing from where are you calling, you can do it from a input like this:
<input type="file" onChange={handleChange} />
If you're already using it like that, I recommend to add console.log(image) outside of a function in order debug what's the content of the variable before sending it to put(). Just as a reference the output from the console.log(image) should be an instance of the File javascript API