I am fetching data using an API in react native. When fetched data in console, its successfully getting data. But while using the code below, the album array is showing undefined.
state = { albums: [] };
componentWillMount() {
//fetch('https://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=881262b246e1d3f2abda8771b1a25fe3&format=json')
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
I am getting console logs like this
{albums: Array(0)}
{albums: undefined}
Why this is undefined?
A Response object has no data property. You access the body of the response by calling the text, json, blob, or arrayBuffer methods and consuming the promise they return.
For instance, if you're receiving JSON:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => this.setState({ albums: data }));
Live Example:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => {
console.log(data);
});
Or we could call the parameter albums and use shorthand property notation:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(albums => this.setState({ albums }));
Related
I have an app build with reactnative, it is running on my local pc, and i would like to fetch and display data from a local symfony api that i have running.
The reactnative code is fetching from my local pc ip, and the symfony port/route:
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
}
}
componentDidMount() {
return fetch('http://10.161.170.86:8000/api/hardwarePlacement')
.then((response) => {
console.log(response.ok);
})
.then((response) => response.json())
.then((responseJson) => {
console.log(response.ok);
this.setState({
isLoading: false,
dataSource: responseJson.hardwarePlacements,
})
})
.catch((error) => {
console.log(error)
});
}
And the json data i get from my symfony API looks like so, when i get it from postman or go directly through the browser:
[{"id":1,"name":"Bryggers","createdDate":{"date":"2023-02-08 15:14:12.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"editedDate":{"date":"2023-02-14 13:57:07.000000","timezone_type":3,"timezone":"Europe\/Berlin"}},{"id":2,"name":"Stue","createdDate":{"date":"2023-02-08 21:52:46.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"editedDate":{"date":"2023-02-08 21:52:46.000000","timezone_type":3,"timezone":"Europe\/Berlin"}},{"id":3,"name":"Stue","createdDate":{"date":"2023-02-14 13:57:10.000000","timezone_type":3,"timezone":"Europe\/Berlin"},"editedDate":{"date":"2023-02-14 13:57:10.000000","timezone_type":3,"timezone":"Europe\/Berlin"}}]
The error i get in my terminal is:
[TypeError: undefined is not an object (evaluating 'response.json')]
If i try with fetching data from an public URL instead, it works fine, it is only from getching data from localhost url, it fails.
Return from the first then
.then((response) => {
console.log(response.ok);
return response
})
.then((response) => response.json())
I'm using a feth request to recieve data from an API.
This is what my request looks like:
fetch(url, requestOptions)
.then(response => response.json())
.catch(error => colsole.log('error', error);
And I'm trying to figure out how to filter certain values from the response.
Here's what the response looks like:
[
{
'Obj.Name': 'objname1',
'Obj.property': 'red'
...
},
{
'Obj.Name': 'objname1',
'Obj.property': 'blue'
...
},
{
'Obj.Name': 'objname3',
'Obj.property': 'green'
...
},
]
I wanna add another ".then" statement there with a function that gets a parameter like ('Obj.Name') that can filter everything by that particular objectname and be able to get other properties of that object.
I want the result to be something like this:
Obj: objectname1, ObjProp: red
Like this?
fetch(url, requestOptions)
.then(response => response.json())
.then((data) => {
const filtered = data.filter(item => item["Obj.Name"] === "objname1")
console.log(filtered)
})
.catch(error => colsole.log('error', error);
Using redux in React.js I get the most starred repositories in the last 30 days, now I wanna use the pagination that github api provides but to do so I have to use the headers in the response, how can I do that, how can I change my code to get the headers from the response, this is the function that gets the response:
import getDate from './getDate';
export function fetchRepos() {
return function(dispatch) {
dispatch({
type: "FETCH_REPOS_REQUEST",
});
return fetch(
"https://api.github.com/search/repositories?q=created:>" +
getDate() +
"&sort=stars&order=desc",
)
.then(response => response.json().then(body => ({response, body})))
.then(({response, body}) => {
if (!response.ok) {
dispatch({
type: "FETCH_REPOS_FAILURE",
error: body.error,
});
} else {
dispatch({
type: "FETCH_REPOS_SUCCESS",
repos: body.items,
});
}
});
};
}
Please help, thank you!
I like to assemble a response object that includes the headers as an object for fetch calls like so:
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => (res.headers.get('content-type').includes('json') ? res.json() : res.text())
.then(data => ({
headers: [...res.headers].reduce((acc, header) => {
return {...acc, [header[0]]: header[1]};
}, {}),
status: res.status,
data: data,
}))
.then(response => console.log(response)));
in your case you could then simply get the headers with response.headers in the last .then().
but technically you can access the headers with res.headers.get('<header.name>').
In Panel.js how can I get data from an API that I wrote in index.js?
Panel.js
index.js
ProfilePanel.js
You can use javascript fetch API
GET example
fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
.then((res) => { return res.json() })
.then((data) => {
console.log(data)
});
})
}
POST example
let key = 'key'
let results = 12;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers : new Headers(),
body:JSON.stringify({key: key, results: results})//use property short hand here
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err)=>console.log(err))
you already get the response and you map the response to state 'results'.you can dispaly the data by simply writing "this.state.results"
Using react and webpack.. why does the code below result in an error: Uncaught (in promise) SyntaxError: Unexpected end of input(…)? Thanks
fetch(feedURL, {"mode": "no-cors"})
.then(response => response.json())
.then(function(data){
this.setState({
data: data
})
}.bind(this));
To better understand your error, add a catch case to your fetch request.
Also, if you use arrow functions, you don't need to bind(this);
fetch(feedURL, {"mode": "no-cors"})
.then(response => response.json())
.then(data => {
this.setState({
data: data
});
})
.catch(resp => {
console.error(resp);
});