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);
});
Related
I am trying to read a value from a response object, but this
fetch("https://api.nft.storage/upload", options)
.then((response) => response.json())
.then((response) => console.log(response))
.then((response) => {
console.log(response.value.cid);
}
... doesn't work. Although my console shows the object being sent:
.. I get this error:
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'value')
1056 | .then((response) => response.json())
1057 | .then((response) => console.log(response))
1058 | .then((response) => {
> 1059 | console.log(response.value.cid);
console.log() doesn't return anything, so response in the next .then() is undefined. Just do both in the same function.
fetch("https://api.nft.storage/upload", options)
.then((response) => response.json())
.then((response) => {
console.log(response);
console.log(response.value.cid);
}
}
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>').
I'm using react js and I want to post text and return a text.
Can anyone help me in posting text and receiving text? I have used
content type text/plain but that didn't help.
Is there any way to do?
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response)
.then(data => {
console.log(data)
this.setState({
code: data
});
});
This is what I have tried to get the text value from api
I am getting an error as
Uncaught promise typeError failed to fetch
fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type. So the code should be changed to.
Also consider adding a catch block for the promise in case of errors and check the console output error (if any ).
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response.json()) // or response.text()
.then(data => {
console.log(data)
this.setState({
code: data
});
})
.catch(err => { console.log('error while fetching', err) });
I am coding this in react.js and I really have no idea what is going on. I am using unirest to make the api call but the fetch isn't working so to me it seems I am doing something wrong in the fetch statement.
unirest.get("https://heisenbug-la-liga-live-scores-v1.p.mashape.com/api/laliga/table")
.header("X-Mashape-Key", "Lzrv6ktkq3mshGiQJrPDa9cBxcDGp1Vcdncjsn1DweG4jU5ref")
.header("Accept", "application/json")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
fetch(unirest)
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json)
this.setState({
record: json.records[0]
});
})
I need to post something on my API.
I have this function which works correctly:
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
I want to move fetch() to another file from where i make all API calls. In that file I already have several fetch functions (with get method) and they work fine.
But when I move this fetch() with post method to that file, I get an error:
TypeError: Cannot read property 'then' of undefined
My code:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
.then(res => res.json()) returns "ok" and 200.
but saveAction(actionInfo) returns undefined. How come?
The function saveAction doesn't return anything (specifically - doesn't return promise) so you can't use then on that function:
export function saveAction(actionInfo){
fetch({
...
})
.then(res => res.json())
}
You can return the fetch (which is a promise) and then you can use then on that function:
export function saveAction(actionInfo){
return fetch({
...
})
.then(res => res.json())
}
If it may be of any help for noobs like me,make sure the return and the fetch statement are on the same line, or surround the fetch statement in parenthesis.
Avoid this! it will also cause the Cannot read property 'then' of undefined error.
function fetchData(){
return
fetch(url)
.then(response => response.json())
}
Try this.
function fetchData(){
return (
fetch(url)
.then(response => response.json()))
}