I want to load only specific number of rows where the condition satisfies.
However the following code fetches all the 25 rows and condition is not working.
Please someone help.
loadCommentsFromServer = () => {
fetch('/api/comments/', {
method: 'GET',
author: 'Dani'
})
.then(data => data.json())
.then((res) => {
if (!res.success) this.setState({ error: res.error });
else this.setState({ data: res.data });
});
}
I am very new to javascript and reactjs, any help will save my weekend.
You don’t have access to the response in your second callback there.
loadCommentsFromServer = () => {
return fetch('/api/comments/', {
method: 'GET',
author: 'Dani'
})
.then((res) => {
if (!res.success) this.setState({ error: res.error });
else res.json().then(data => this.setState({ data }));
});
}
Related
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:
function get(){
fetch('http://localhost:8082/marca/listar', {
method: 'GET',
headers: {},
mode: 'no-cors', // <---
cache: 'default'
})
.then(Response => { return Response.json() })
.then(data => {
console.log(data.nombre)
});
}
This is the url of the api
And I get the following error:
console message image
Per https://developer.mozilla.org/en-US/docs/Web/API/Body/json have you tried:
response.json().then(data => {
// do something with your data
});
it is because the response you get from the server is an array not JSON object
so treat it as such
fetch('http://localhost:8082/marca/listar',
{ cache: 'default' })
.then(function (response) {
if (response.status !== 200) {
return;
}
response.json().then(function (data) {
data.forEach((element) => {
element.whatYouWant; /* Change (whatYouWant) to your desired output */
})
})
})
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
I would like to explain my problem of the day.
in the following code I map a table, and I post all of this in a database
everything works fine. the only problem and the format in which I receive it.
{
"id": 136,
"items": "[{\"title\":\"Campus (Pinte)\",\"quantity\":2}]",
}
I would rather recover it in another format than in arrays. here is my code:
postbackend = () => {
const newItems = this.props.items.map(item => {
const { title, quantity } = item;
return {
title,
quantity
};
});
const config = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ ...this.state, items: newItems })
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
} else {
alert(`film ajouté avec l'ID ${res}!`);
this.props.history.push("/OderSummaryScreen"); // Your Success Page
}
})
.catch(e => {
console.error(e);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
})
.finally(() =>
this.setState({
redirect: true
})
);
};
Do you have an idea of how to fix this?
New to React, I'm currently trying to create a data table with data from an API.
I want to have a first fetch, and then run another with response from the first (id) in order to complete my table.
Here is my code :
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
data: []
};
}
componentDidMount() {
this.setState({
user: JSON.parse(localStorage.getItem('user'))
}, function () {
this.loadAllObjectsInfo()
});
}
// Fetch all object info in order to fill the table
loadAllObjectsInfo() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'bbuser': this.state.user.userId,
'bbtoken': this.state.user.secret
},
};
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((data) => {
this.setState({ data: data })
})
}
With this code, I have the data I want to render my table but I need to run another fetch to get other info with the id coming from the first request.
How can I do that nested fetch request ?
Thanks a lot,
Matthieu
You can easily manage this with async/await:
async loadAllObjectsInfo() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'bbuser': this.state.user.user
'bbtoken': this.state.user.secret
},
};
let response = await fetch('https://xxxxx/api/objects', requestOptions);
let data = await response.json();
// here is another fetch - change to fit your request parameters (this is just example)
let info = await fetch('https://xxxxx/api/objects/' + data.id);
this.setState({ data });
}
You can read more about async function.
#JourdanM, you should return a new fetch request from one of the then handlers. I've made a simple snippet for you. There are no data validators and spinners. This is a simple showcase. =)
A fetch request returns a promise, and you can chain promises by simply returning them from the then handlers. Here is a good article about it, it has great examples: https://javascript.info/promise-chaining
function fetchUser (user) {
return fetch(`https://api.github.com/users/${user.login}`)
}
class User extends React.Component {
state = {
user: null
}
componentDidMount () {
fetch("https://api.github.com/users")
.then(response => response.json())
.then(users => fetchUser(users[0]))
.then(response => response.json())
.then(user => {
this.setState({user})
})
}
render () {
return (
<div>
<pre>{JSON.stringify(this.state.user, null, 2)}</pre>
</div>
)
}
}
ReactDOM.render(<User />, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can write the code as below.
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((res1) => {
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((res2) => {
this.setState({ data: res2 });
});
});
Hope this will work for you!
You can also use axios like below
axios.post(url, data, header).then(res => {
if(res.status === 200){
console.log('1st data')
axios.post(url, data, header)
.then(response => {
if (response.status === 200) {
console.log('2nd data')
} else {
console.log('2nd error')
}
});
}else{
console.log('1st error')
}
});
getData() {
return fetch("http://bitcfeedcms.rf.gd/script.php")
.then(response => {
console.log(response);
response.json();
})
.then(responseJson => {
this.setState({ data: responseJson });
})
.catch(error => {
console.error(error);
});
}
I also tried by putting ?l=1 like " bitcfeedcms.rf.gd/script.php?l=1 ".
The main json file is " bitcfeedcms.rf.gd/feed_data.json ". So i tried "http://bitcfeedcms.rf.gd/feed_data.json?l=1" this too but nothing changed
What i have to do now to get the json data and use it in my app...Please help
You are using the arrow function wrong. Instead of this:
fetch("http://bitcfeedcms.rf.gd/script.php")
.then(response => {
console.log(response);
response.json();
})
.then(responseJson => {
this.setState({ data: responseJson });
})
You should return the response.json()
fetch("http://bitcfeedcms.rf.gd/script.php")
.then(response => {
console.log(response);
return response.json();
})
.then(responseJson => {
this.setState({ data: responseJson });
})
This way you can reach responseJson in the next then.
Also, if your app complains about fetch() network request failed probably it's about Info.plist or Manifest configuration error. See this topic.
For iOS, you can try the same request with this https dummy json url:
https://jsonplaceholder.typicode.com/posts/1
http://bitcfeedcms.rf.gd/script.php , this link returns multiple sets of JSON.
([{"FeedTitle":"Debotos","FeedDescription":"First Feed Testing....."},{"FeedTitle":"Akash","FeedDescription":"Creating a clan named \"Khulna Sparkers\""},{"FeedTitle":"Ripon","FeedDescription":"My brother and my one of the closest individual"}])
try this . . .
getData() {
fetch("http://bitcfeedcms.rf.gd/script.php")
.then(response => {
console.log(response);
response.json();
})
.then(responseJson => {
var length = responseJson.length;
for (var a = 0; a<length;a++) {
var FeedTitle = responseJson[a].FeedTitle; //<-variable from your response json
var FeedDescription = responseJson[a].FeedDescription; //<-from your response json
console.log(FeedTitle);
console.log(FeedDescription);
}
})
.catch(error => {
console.error(error);
});
}
try axios
npm install --save axios
state = {data:[]};
componentWillMount() {
axios.get('http://bitcfeedcms.rf.gd/script.php')
.then(response =>this.setState({data:response.data}));
}
I have a common function which uses FETCH to get data from external web service. this function will be invoked and parsed in multiple screens under componentDidMount(). instead of repeating the same code at multiple places, I put below under a common class, but unfortunately, data is not returned to those screens.
Common Function
export function convertValue(fromVal, toVal) {
var requestObj = {};
let apiEndpoint = '<target endpoint>'
return fetch(apiEndpoint, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.log('Error: ', error);
});}
Sample call below, and no pop-up when screen loaded.
componentDidMount () {
AsyncStorage.getItem('user_default').then((value) => {
this.setState({userDefault: value});
}).then((value) => {
var sample = convertValue('A', 'B');
Alert.alert(
'Success',
JSON.stringify(sample),
[
{text: 'OK',
onPress: () => {
console.log('.');
}}
]
)
});}
componentDidMount () {
AsyncStorage.getItem('user_default').then((value) => {
this.setState({userDefault: value});
convertValue('A', 'B').then((json)=>{
alert(json)
})
})}
This might work for you. The problem was improper chaining of asynchronous calls.
Nick is right, found the right way -
convertValue('A', 'B')
.then((responseJson) => {
this.setState({returnedValue: responseJson.convertedValue});
});