I am making a component that should transfer the data in file controllers/hello.js(backend) to App.js(frontend in React.js app) which is imported from the router/collector components/hello.js
My components/hello.js looks like this:
import { React } from 'react'
import { useEffect, useState } from 'react';
export const Hello = ()=>{
const[initialState, setInitialState] = useState([], )
useEffect(()=> {
fetch('http://localhost:3001/api/', {mode: "no-cors"})
.then(response => response.json()).then(data => console.log(JSON.parse(data)))
// if (res.ok){
// return res.json()
// }
// }).then(jsonResponse => console.log(jsonResponse))
},[])
// console.log(initialState)
console.log("should work ")
return (<div>Hello</div>)
}
And I get this error:
Uncaught (in promise) SyntaxError: Unexpected end of input
at hello.js:9:1
when I check the API the only response I get is this
but it should be matching what's in localhost:3001/api/ or what's in controllers/hello.js which is
Do you have any idea how I can solve this? Any help is appreciated.
Related
import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const mdxToJsx = async (value) => {
const { default: Content } = await run(value, runtime);
return Content
};
export default mdxToJsx;
Here as per mdx library, I want to convert mdx to jsx but I got Uncaught (in promise) SyntaxError: Unexpected identifier 'Promise'
at new AsyncFunction ()
at run (run.js:15:1)
Kindly help me. Thanks Happy coding.
import React, { Fragment, useEffect, useState } from "react";
import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
export default function MdxToJsx({code}) {
const [mdxModule, setMdxModule] = useState()
const Content = mdxModule ? mdxModule.default : Fragment
useEffect(() => {
(async () => {
setMdxModule(await run(code, runtime))
})()
}, [code])
return <Content />
}
I tried this one also but got the same error.
The app work perfectly locally. The error appears after i deploy it using firebase hosting. The code below is the component where i fetch the data from the api resource
import React, { useEffect, useState } from 'react'
import{ useSelector, useDispatch} from "react-redux"
import { setProducts } from "../containers/redux/actions/productActions"
import ProductComponent from './ProductComponent';
import axios from 'axios';
function ProductList() {
const products = useSelector((state) => state);
const dispatch = useDispatch()
const [searchValue, setSearchValue] = useState('');
const fetchProducts = async ( searchValue) => {
const response = await axios
.get(`http://www.omdbapi.com/?s=${searchValue}&apikey=??????`)
.catch((err) => {
console.log("Err", err);
});
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
};
useEffect(() => {
fetchProducts(searchValue);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[searchValue]);
console.log("Products: " , products)
return (
<div className='home'>
<div className='search-box'>
<input
value={searchValue} onChange={(e) => setSearchValue(e.target.value)}
type="text"
placeholder="Search.."
>
</input>
</div>
<div className='products-list'>
<ProductComponent />
</div>
</div>
)
}
export default ProductList
Error message appears on the console of the deployed app :
ProductList.js:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
Try to check your response first.
I think you may have to prove catch error here. Adding else statement in case of response.data.Search is undefined or use response?.data.Search
Most browsers will block insecure requests (http) made from secure sites (https).
Change http://www.omdbapi.com/ to https://www.omdbapi.com/
import logo from './logo.svg';
i need to list items from my appsync api in my react app ...i cant display as it says the error its undefined ...which i mentioned bellow the code..i know my code is wrong can somebody guide me
import React, { useState } from "react";
import { API, graphqlOperation } from 'aws-amplify';
import { listTestModels } from "./graphql/queries/list";
import './App.css';
function App() {
const [list, setBook] = useState(null);
const getBook = async () => {
// make a call to appsync api
const list = await API.graphql(graphqlOperation(listTestModels));
setBook(list.data.listTestModels.items);
}
const viewBook = () => {
if (list) {
**it shows error after this **
return (<article>
<h3>{list.data.listTestModels.items}</h3>
<p>{list.Location}</p>
<p>{list.Email}</p>
</article>)
}
}
return (
<div>
<section className="book-section">
<button onClick={() => getBook()}>Get book details</button>
<hr />
{viewBook()}
</section>
</div>
);
}
export default App;```
**it shows error App.js:24 Uncaught TypeError: Cannot read properties of undefined (reading 'listTestModels')**
list.data is undefined. Change the condition to list && list.data
const viewBook = () => {
if (list && list.data) {...}
}
But if the data key doesn't exist in the list object . It will never render the viewBook.
In my App.js function, when it first loads, I want to fetch a website. This website contains .json data. The console gives the following error when I try to fetch the website:
App.js:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
App.JS:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
When I visit the website through the web browser, I'm able to see the JSON.
My App.js Code:
import logo from './logo.svg';
import './App.css';
import Weather from './Weather'
import React, { Component, useState } from "react";
function App() {
const [details, setDetails] = useState("0");
fetch("https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313")
.then(response => response.json())
.then((data) => {
setDetails(data)
console.log("hi")
} );
return (
<div className="App">
<div className="weatherWrap">
<Weather longg="0" lat="0" name="China"/>
</div>
</div>
);
}
export default App;
I'm assuming I'm fetching the website incorrectly. I also think that the way I did it, it will keep fetching every time. While I only want it to fetch once. Please let me know how to fix it. Thanks!
Try below piece of code:
const url = 'https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313';
function App() {
const [details, setDetails] = useState([]);
const getDetails = async()=>{
const response = await fetch(url);
const details = await response .json();
setDetails(details );
}
useEffect(() => {
getDetails();
},[]);
}
Here is the code that will work for you. Link
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [details, setDetails] = useState("0");
useEffect(() => {
fetch(
"https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}, []);
return (
<div className="App">
<div className="weatherWrap">hello world</div>
</div>
);
}
I'm trying to make my code a bit more reusable, and as such, I want to store multiple async functions into another file.
blog.ts
import db from '#/firebase/init'
async function getTags (uid) {
const tags = db.collection('tags').where('blogId', '==', uid)
const data = []
await tags.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.data())
data.push(doc.data().tag)
})
return data
})
.catch(err => {
console.log('Error getting documents', err)
})
}
export default getTags
anotherpage.vue
<script>
import { getTags } from '#/functions/blog'
mounted () {
if (this.$route.params.blog) {
this.blog = this.$route.params.blog
}
getTags(this.blog.uid)
}
Returns with the error that
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Object(...) is not a function"
found in
---> <EditBlog> at src/components/admin/admin/Blog/EditBlog.vue
<CreateBlog> at src/components/admin/admin/Blog/CreateBlog.vue
<LayoutDefault> at src/App.vue
<Root>
Can anyone point me in the direction of a guide of how to correctly import these functions?
You're trying to use a named import when you import but are making the module as a default export. To fix this, you can just
import getTags from '#/functions/blog'.
Technically getTags is not a Named export, it's the default export. If you're planning to have a bunch of functions in one file, and want to use named exports/imports you just have to remove the default from your function.
Now you will be able to pick and choose what to import since they are named exports!
There's a simple blog post that goes over this pretty quickly here
This is how your file(blog.ts) with multiple named exports (with your functions) would look like.
export async function getTags (uid) {
const tags = db.collection('tags').where('blogId', '==', uid)
const data = []
await tags.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.data())
data.push(doc.data().tag)
})
return data
})
.catch(err => {
console.log('Error getting documents', err)
})
}
export async function getLaundry(uid) {
//stuff
}
Then in your file that you want to import just the ones you want, let's say you just want getLaundry you can do so like:
import { getLaundry } from '#/functions/blog'
Or both like:
import { getLaundry, getTags } from '#/functions/blog'