React failing to parse a JSON object from server - json

I'm running into this error:
Uncaught (in promise) SyntaxError: Unexpected token [ in JSON at position 1
when I pass a JSON object containing an array of JSON objects to my component. The object structure is:
{ "arrayName": [{object},{object},{object}, etc...] }
I've run the JSON through a validator and it comes up clean but my api call always returns the same error.
export const api = 'http://localhost:8000'
export const headers = {
'Content-Type': 'application/json',
'Accept' : 'application/json',
}
export const getAll = () =>
fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
This is where it gets called in App.js:
componentDidMount() {
eventsAPI.getAll().then((events) => {
console.log(events)
this.setState({ events })
})
}
I'm not sure why I'm getting the error, I know I'm sending a valid JSON object, is the way I'm receiving it wrong? I can see in the network tab of the dev tools that the correct format is being passed and received. I just don't know where exactly I've gone wrong. This is the response logged from the server. I can see the XHR response in dev-tools but it's a bit big to post here 25+ objects.

You need to modify getAll to actually return something. As it is a fetch, you can just return that, which will return the promise.
export const getAll = () =>
return fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
Now wherever you use getAll be sure to call then:
getAll().then(data => console.log(data))

Related

Data sent from flask not received from react

I'm using flask as the backend and the database is using firebase. I want to get the data sent by app.py from React, but it keeps failing.
app.py
#app.route("/StoreListView")
def list_stores():
storedata = DB.get_store() #read the table
tot_count = len(storedata)
return render_template(
"index.html",
storedatas=storedata.items(),
total=tot_count)
StoreListView.js
function Stores(){
useEffect(() => {
fetch("/StoreListView", {
headers: {
Accept: "application/json",
}
})
.then(response => response.json())
.then(jsonData => {
console.log(jsonData)})
.catch(
(err) => console.log(err))
}, [])
}
I see this error.
SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON
I think it's a problem to render html in the list_stores function... but if I just do the return stored data, the front screen coded with the react does not come out and the data is just printed out...

Is there a way to get a nested JSON object using react native?

My JSON file can be found using this link. The object "features" have a nested object called "properties", where I want to access the data from that object. I've tried to use the useEffect() hook from React and implemented that in the code below. I tried to get the "properties" sub object by implementing the following code: data.features.properties, but that returns undefined. What code am I implemented wrong or what logic is incorrect?
useEffect(() => {
fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
.then((response) => response.json())
.then((json) => {
setData(json);
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [stateAbb]);
stateAbb is the state abbreviation for the state that the user selects in a text input on a different screen. propData seems to store the "features" object as I have used the alert() function and typeof() to determine that propData is an object.
I've tried to JSON.parse() and implemented some other StackOverflow answers, such as this and this. The effect still remains the same. data.features works as an object but data.features.properties returns undefined.
Any help would be appreciated!
Thanks!
React hooks doesn't allow async await in useEffect so you can create new function like this
useEffect(()=>{
fetchData()
},[])
const fetchData = async ()=>{
try{
const response = await fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
const json = await response.json()
console.log(json); // your data is here!
}catch(err){
console.log(err)
}
}

Handling Deeply nested Json Objects using useState in Reactjs

Am trying to get value from nested json. but got 'undefined' error. when i display the same object in console, it works fine. I want to fetch particular field from nested json object.
here is the json output from api, i want to fetch userid, name and verified fields from below json
{
status: true,
user:
{
id: 11362
phone: "+918971557357"
name: "Sagar pawar"
email: null
bio: null
address: null
date_of_birth: null
token: "EMAWdBl3LDjl1X5veo6VvZBKfgQns5wTFXKWjIh9w4VKKXlclRo5ZBlWaJUBS5ImaVZANN9DlHSbFWquObaW1FIJLVGPqFLWKoPEzKLvZAJakhoTxg5TRTjVtLEVz9R9zAbocwF7dmRdI4GCAMlJdtKOEZAUuOcf6AZD"
image: ""
role: "user"
notification_cleared: {date: "2019-12-28 11:42:34.899503", timezone_type: 3, timezone: "UTC"}
deleted_by: null
blocked: 0
verified: 0
}
}
and this is the fetch function i tried.
fetch(url, options)
.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {
const jsonobj = data.user.id;
console.log("User ID:", jsonobj);
})
and this one i have tried.
const [responseUserId, setUserId] = useState(userId);
...
fetch(url, options)
.then(res => res.json())
.then(res =>
setUserId({ userId: res.user['id'] })
)
thanks in advance.
First and foremost. In your fetch function when you log data, in the second then you don't return any data, so in the third then your callback argument is undefined. After console.log("Data Response", body), you should add return body, so it get's passed down as data in your next then statement.
Second, your id is a string(or number, it doesn't matter). So your responseUserId will be a string. So when setting the state with useState you don't need to pass in an object, just pass the value. Like this : setUserId(res.user['id'])
Hope this helps!
i create a simple fetch request and setUserId just like you want and it works.
the problem is you use 3 then methods you only need 2.
in the third then data is undefind but in second you have what you need.
.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {
https://codesandbox.io/s/reverent-mestorf-o43s1
it is so simple i hope it help you
I will use your last example of a functional component with useState:
You initialize responseUserId with userId. Given the code you provided, that should fail to compile, because userId is not defined. Give it a value, like null, or 0 or an empty string.
If you return an object with only one property, you probably don't need the object data type. In my example data.userId and consequently responseUserId is of type Number.
import React, { useEffect, useState } from 'react';
export default function App() {
const [responseUserId, setResponseUserId] = useState(null);
useEffect(() => {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetch(url)
.then(res => res.json())
.then(data => setResponseUserId(data.userId))
.catch(err => console.error(err));
}, []);
return responseUserId && <h3>{responseUserId}</h3>;
}

Feathersjs socketio how to correctly set params.route?

I have a Feathersjs API which using REST can serve a GET request to a URL like http://server.com/service-name/:fieldName where fieldName has a string value. The API assigns the value of fieldName to params.query.
While developing a React Native app, I am trying to make the same request using feathers socketio client. The request looks like this:
return this.app.service('service-name/:fieldName').find({
query:{fieldName='value'}
}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
The request above makes it to the server, but the value of fieldName is either undefined or some other unwanted value because the server returns an empty result set. I have also read that the setSlug hook would be an option, but I am not sure how to do it.
Can someone please help me resolve this issue by sending the real value of fieldName in the request to the server?
[Edit]
After checking the logs on the API server, I found out that a REST API request has the correct params.route object:
object(9) {
["query"] => object(0) {}
["route"] => object(1) {
["fieldName"] => string(5) "value"
}
...
The params.route is empty with the socketio request:
object(9) {
["query"] => object(0) {}
["route"] => object(0) {}
["connection"] => object(6) {
["provider"] => string(8) "socketio"
["payload"] => object(1) {
["userId"] => number(3)
}
...
While I'm relieved to know where the problem is, would anyone please tell me how to correctly set params.route in React Native using a socketio request?
You can use a normal route just like with HTTP which will set params.route with fieldName:
return this.app.service('service-name/something').find({}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
Will set { params: { route: { fieldName: 'something' } } }

Angular2 Http.Post - How to view webapi response

I'm new to Angular2/Typescript and I'm writing my first web application.
I'm trying to call a webapi using POST, it works, if I intercept the call using FIDDLER I can see the Json response.
Now, how I can log in the browser console the json ouput?
The code is this:
code call
var s = this.myService.doSearch();
s.subscribe(
data=> this.data = data,
error => this.errorMessage = <any>error
);
console.log(s);
service method
doSearch() {
var url = this.baseUrl;
return this.http.get(url)
.map(response => response.json())
.catch(this.handleError);
}
My question is: how and where I can view and manage the Json Output ?
Thanks
You need to console.log it after the async code is finished:
var s = this.myService.doSearch();
s.subscribe(
data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
If you are debug or run your application in browser you can got to inspect and then move to the Network tab. In this tab select your POST Request and the go to the tab Response and voila there is your json Response
Edit:
To log all response data do this:
return this.http.get(url)
.map(res => res.json())
.subscribe(data => { console.log(data);})
.catch(this.handleError);
}
Try this this will print what you have in your returned observable .
var s = this.myService.doSearch();
s.subscribe(data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
Always remember If you want to get data from observable.you need to subscribe it.
you can't log it like this console.log(s); because s returns an observable. you should subscribe and refer those data inside the subscribe .