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>;
}
Related
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)
}
}
componentDidMount() {
fetch("http://localhost:5000/customers/:id")
.then((res) => res.json())
.then((info) => {
this.setState({ info });
})
.then((err) => console.log(err));
}
How to fetch a specific data from database by sending the required ID with URL?
You can use the format string syntax from javascript and add the id to the url-string with that.
const id = 42
fetch(`http://localhost:5000/customers/${id}`)
I have a function which makes an API call to fetch an item and then stores that object array in a state variable 'data'. But the variable is not getting updated. On logging, it shows an empty array. On logging the API call result, I get the required response. That means i'm getting the data from the call but just can't put that in my 'data' variable.
Here's the function
componentWillMount(){
window.scrollTo(0,0);
const itemId = parseInt(this.state.id);
Axios.get(`http://localhost:5000/item/getitem/${itemId}`)
.then(res => {
this.setState({
data: res.data
})
})
.catch(err => console.log(err));
}
I'm not able to pick out a certain key/value from a fetched JSON file, and then assign it to a variable.
const fetch = require("node-fetch");
var url = 'https://randomuser.me/api/'
fetch(url)
.then((response) => response.json())
.then((hmm) => console.log(hmm.results))
The above code serves to return info from the top branch, "results", but I can't get any deeper.
Modifying it to .then((hmm) => console.log(hmm.results.gender)) returns undefined.
I'd then like to assign the Value from the "gender" Key to a variable.
results is an array.
You need to do results[0].gender
.then((hmm) => console.log(hmm.results[0].gender))
const fetch = require("node-fetch");
var url = 'https://randomuser.me/api/'
fetch(url)
.then((response) => response.json())
.then(function (hmm) {
var data = hmm.results[0].gender;
console.log(data)
})
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))