App.js:13 Uncaught (in promise) SyntaxError: Unexpected end of input - javascript

Sending a fetch request to this API, though as the title states, keep getting unexpected end of input and I can't figure out why. Any solutions?
import './App.css';
import React, {useEffect, useState} from 'react';
const ART_API = "https://api.harvardartmuseums.org"
function App() {
const [anime ,setAnime] = useState([])
useEffect(() => {
fetch(ART_API, {mode: 'no-cors'})
.then((res) => res.json())
.then((data) => { console.log(data)})
}, []);}

Related

How can I use 'withRouter' and 'history push' in react router v6 for redirecting

I have registered a button that will take users to a login page on click. I tried using history.push() and include values entered into the form, but I do not know how to pass the value of userData because I get the following error:
refers this line payload: err.response.data()
When I change this line to display data in the console it is displayed correctly.
authAction.js
import axios from 'axios';
import { GET_ERRORS} from "./types";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import React from "react";
// Register User
export const registerUser = (userData,history) => dispatch => {
axios
.post('/api/users/register', userData)
.then(res => history.push('/login'))
// .then(res => console.log(res.data))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data()
})
);
};`
I tried to import the hooks version with router but it brings another error "Invalid Hook Call Warning"
export const registerUser = (userData,history) => dispatch => {
const navigate = useNavigate();
axios
.post('/api/users/register', userData,navigate)
.then(res =>navigate('/login'))
// .then(res => console.log(res.data))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data()
})
);
};
What am I doing wrong?

How I can get response http url by axios in the server

I have a problem with axios in REACT, it works on local but does not work when I deployed it.
It say this : enter image description here
my Code :
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get("https://recvueadmin.hellow.fr/api/question")
.then((res) => console.log(res))
.catch((err) => console.log(err))
}, []);
I have this for CORS in the back-end :
app.use(cors());

ReactJS rendering Issue fetching an API

I'm trying to fetch a WeatherApp API, using Geolocation.
My problem is the rendering:
It doesn't allow me to render the page before I fetch (but after I somehow manage to fetch, the code seems to work).
Returning Error message:
Type Error : Cannot Read Property 'temp' of undefined
import React, { useState } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
// this line is returning the error
console.log(weather.main.temp)
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
Fetching weather and setting weather state is asynchronous, your are console logging weather.main.temp before the request has completed. And fetching data is side effect in reactjs. So you are suggested to fetch weather info by using useEffect hooks and set weather state there.
import React, { useState, useEffect } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
useEffect(() => {
fetchingWeather();
}, [weather])
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
That should work.

'login' is not defined error happens in React.js

I made frontend app in React.js.
I wrote codes in App.js of frontend like
import React, { Fragment, useState, useEffect, Component, View } from 'react';
import axios from 'axios';
import Routes from '../src/components/Routes';
import TopNavigation from './components/topNavigation';
import SideNavigation from './components/sideNavigation';
import Footer from './components/Footer';
import './index.css';
import Router from './Router';
const App = () => {
const [user, setLogin] = useState(null)
const [report, setReport] = useState(null)
useEffect(()=>{
login().then(user => setLogin(user))
}, [])
useEffect(()=>{
getReport().then(report => setReport(report))
}, [])
return <div>
{user != null? <p>name: {user.name}</p>:<button>Login</button>}
</div>
}
export default App;
I wrote in this code login().then(user => setLogin(user)) whether user already logined or not.
Login system was made in Django,so I want to use it.I think React has login method but I really cannot understand what is wrong.How should I fix this?
I can see nowhere login is defined in your code. If you've written login on other files, you should import it.
Actually, I cannot understand what you mean by this - "I think React has login method but ...". React doesn't support any predefined login method.
You should define login method yourself something like this.
const API_URL = 'some url';
const login = async (body) => {
const response = await axios.post(`${API_URL}/login`, body);
return response.json();
};
const App = () => {
const [user, setLogin] = useState(null);
const [report, setReport] = useState(null);
useEffect(() => {
login({
email: 'email#some.com',
password: 'some password'
}).then((user) => setLogin(user));
}, []);
useEffect(() => {
getReport().then((report) => setReport(report));
}, []);
};

Unhandled Rejection (TypeError): respo.json is not a function

I'm a beginner in React and stuck with some problem. Getting an issue Unhandled Rejection (TypeError): respo.json is not a function.
import React, { useEffect } from "react";
import { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios";
function App() {
const { monster, setMonster } = useState([]);
useEffect(() => {
async function fetchData() {
const respo = await axios.get("https://jsonplaceholder.typicode.com/users");
const resp = await respo.data;
setMonster({ monster: [...resp] });
}
fetchData();
}, [monster]);
return (
<div className="App">
<p>{console.log(monster)}</p>
</div>
);
}
export default App;
Use respo.data instead :
Your response has a data key which you need to fetch.
import React, { useEffect } from 'react';
import {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
function App() {
const [monster,setMonster]=useState([]);
useEffect(()=>{
async function fetchData() {
const respo=await axios.get('https://jsonplaceholder.typicode.com/users')
const resp=await respo.data;
setMonster({monster:[...respo]});
}
fetchData();
},[]);
return (
<div className="App">
<p>{console.log(monster)}</p>
</div>
);
}
export default App;
Working code : https://codesandbox.io/s/elated-platform-1itbi?file=/src/App.js
There are two problems in your code:
const {monster,setMonster}=useState([]);
This should be:
const [monster,setMonster] = useState([]);
const resp = await respo.data;
This should be:
const resp = respo.data;
respo.data is not a promise, but already the result of the api.
Note:
To update monster, you have to call setMonster(resp) not setMonster({ monster: resp })
How about just using get/then instead of async/await?
useEffect(()=>{
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
setMonster({
monster:[...response.data]
});
});
}
},[monster]);

Categories