I'm trying to consolidate some code in one of my react components because my componentDidMount method is getting a bit verbose. This gave me the idea to create an api that does all of my data fetching for the entire app.
I'm having an asynchronous issue I'm not sure how to resolve.
I created the separate api file (blurt.js):
exports.getBlurts = function() {
var blurtData = null;
fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((data) => {
blurtData = data;
});
return blurtData;
}
and imported it to my (.jsx) component via
import blurtapi from '../api/blurt.js';
The problem is that when I call blurtapi.getBlurts() within componentDidMount(), the value comes back as null. However, if I write the data to the console like so:
.then((data) => {
console.log(data);
});
all is as it should be. So, the function is returning before the db operation completes, hence the null value. How would I reign in the asynchronous aspect in this case? I tried an async.series([]) and didn't get anywhere.
Thanks
So fetch returns a promise, which it is async , so any async code will run after sync code. so this is the reason you get null at first.
However by returning the async function , you are returning a promise.
Hence this code:
exports.getBlurts = async () => {
const data = await fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
const jsonData = await data.json();
return jsonData;
}
To retrieve any promise data, you need the then function,
so in your componentDidMount, you will do:
componentDidMoint() {
blurtapi.getBlurts()
.then(data => console.log(data)) // data from promise
}
Promises:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
async/await:
https://javascript.info/async-await
I hope this makes sense.
fetch call returns a promise. therefore in your function u do something like this
exports.getBlurts = function() {
var blurtData = null;
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
}
And do this in your componentDidMount
componentDidMount(){
blurtapi.getBlurts().then((data)=>{
this.setState({data})
}
}
In your example return blurtData; line will run synchronously, before the promise is resolved.
Modify getBlurts as:
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((data) => {
return data;
});
}
And in componentDidMount:
componentDidMount() {
getBlurts.then((data) => {
// data should have value here
});
}
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(res => return res)
async componentDidMount() {
const response = await blurtapi.getBlurts();
}
or
exports.getBlurts = function() {
return fetch('/getblurts/false', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
componentDidMount() {
const data = blurtapi.getBlurts()
.then(data => {
// Do something or return it
return data;
});
}
Related
I need help because I couldn't use a separate function to generate the token - it gives out a promise, not a value. I was told that a value can only be used inside a function.
For each request, I generate a new token in the first request and then pass that token into the second request.
I tried making a separate function to generate the token, but fetch returns a promise.
As a result, I made such a big function and it works.
Is there a way to make a separate function for the first request and pass the result to the second request?
The first token generation function is required frequently, while the second request is always different.
fetch('/api/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'id': '5' }),
})
.then(response => response.json())
.then(result => {
fetch('/api/reviews', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + result.token,
},
body: JSON.stringify({ 'limit': 10 }),
})
.then(response => response.json())
.then(result => {
this.setState({ data: result.data });
})
})
create a function that return promise
async function getToken() {
return await fetch('/api/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'id': '5' }),
})
.then(response => response.json())
.then(result => {
return Promise.resolve(result.token);
}).catch(error => {
return Promise.reject(error);
})
}
async function getReview() {
const token = await getToken().then(token => {
return token
}).catch(error => {
//handle error
});
fetch('/api/reviews', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify({ 'limit': 10 }),
})
.then(response => response.json())
.then(result => {
this.setState({ data: result.data });
})
}
i did not test this code but you get the idea
i will test and update my answer asap
Yes you can with async / await. It will allow you to lift the lexical scope of the API response from inside the .then "callback hell" and into the parent function scope.
Your separate function which fetches the token will return a promise, but then the requesting function will wait for the promise to execute and resolve before continuing.
async function fetchToken() {
const response = await fetch('/api/token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'id': '5' }),
})
return await response.json();
}
async function getReviews() {
const response = await fetch('/api/reviews', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + result.token,
},
body: JSON.stringify({ 'limit': 10 }),
})
const result = await response.json();
this.setState({ data: result.data });
}
Additionally, if the token call does not need to be made every time the reviews call is made, then you can memoize the value, and use that memoized value.
const tokenMemo = useMemo(async () => await getToken(), []);
async function getReviews() {
const response = await fetch('/api/reviews', {
// ...
'Authorization': 'Bearer ' + tokenMemo,
// ...
}
I have been trying to start using typescript for react native but it has not been easy ride so far, finding it difficult to perform common function like fetch an api once on screen load, below is the current function am using but I dont want to use time outs plus its not even working properly(it has to wait for the actual time I set before it runs and its bad for android), I would like to call the function only once when the page loads, I have also tried using if else statements but I dont know why it not just working on typescript.
(function(){
setTimeout(function () {
const newsUrl = 'http://172.20.10.4:8000/mobile/news';
return fetch(newsUrl, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
})
.then((response) => response.json())
.then((data) => {
let newArr = [...data];
setProducts(newArr);
//console.log(data);
alert(38783763);
})
.catch((error) => {
alert(error);
console.error(error);
});
}, 200);
}.call(this));
You can use the useEffect hook and pass an empty array the fetch data once on load.
useEffect(() => {
fetch(newsUrl, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
})
.then((response) => response.json())
.then((data) => {
let newArr = [...data];
setProducts(newArr);
})
}, []);
I have this function in my context provider I want it to return a promise so that I can access the returned data from axios
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
And the result I'm looking for is to write such code in every other component whenever I needed
sendRquest('usermanagement',data,'post','foo/bar').then(res=>console.log(res.data)).catch(err=>console.log(err))
You have to return the promise.
Something like
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
},
data: data
};
return axios(config)
.then(function (res) {
return res
})
.catch(function (error) {
return error
});
}
Be careful tho because you are "swallowing" errors by using .catch like this. The promise returned by sendRquest will never "fail" (reject) but will succeed (resolve) with either data or error payloads.
the complete answer is like this
may help you all
const sendRquest =(service,data,method,url)=>{
let base = api.find(item => item.name ===service )
let config = {
method: method,
url: `${base.url}/${url}`,
headers: {
'x-clientId': clientId,
'Content-Type': 'application/json',
'Authorization': token
},
data: data
};
return axios(config)
}
I need to return the result of a function from another page in react native which performing a fetch call. I use the method as follows. As I know this is because asynchronous call. Is there a special way to achieve this in react native ?
fetchcall.js
import address from '../actions/address'
const dashboard = {
getvals(){
return fetch(address.dashboardStats(),
{method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( {...
}),
})
.then((response) => response.json())
.then((responseData) => {
console.warn(responseData);
return responseData;
})
.catch((error) => { console.warn(error); })
.done();
// return 'test_val'';
}
}
export default dashboard;
dashboard.js
import dashboard from '../../services/dashboard';
class Dashboard extends Component {
componentDidMount(){
console.warn(dashboard.getvals());
}
}
export default connect(mapStateToProps, bindAction)(Dashboard);
Its display the result as "undefined", but that fetch call works and it displays the result. Any suggestion?
In fetchcall.js you are returning a Promise. Also since you are returning the responseData in the .then() method itself, you don't need the .done() method.
Since getvals() is returning a Promise, you need to access it's value in a .then() method.
Overall, your code should be like this:
function getvals(){
return fetch('https://jsonplaceholder.typicode.com/posts',
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
return responseData;
})
.catch(error => console.warn(error));
}
getvals().then(response => console.log(response));
The best architectural pattern, I think, is to use a callback function, usually by writing in as an anonymous function.
///Component.js
my_service.login((data=>{
this.setState({body: data.body});
}));
////Service.js
export const login = function (cb){
fetch('http://myapi.com/103?_format=hal_json')
.then((response) =>{
return response.json();
})
.then((data) =>{
cb(data);
});
}
I am still a junior developer, but use this pattern frequently. If someone has a reason for a different approach, I would love to hear it.
fetch always return a Promise doesn't matter what you are returning.
so you can return a string, variable or something else but you have to use .then to access data
file where you make fetch request
export const graphql = () => {
return fetch("https://graphqlzero.almansi.me/api", {
"method": "POST",
"headers": { "content-type": "application/json" },
"body": JSON.stringify({
query: `{
user(id: 1) {
id
name
}
}`
})
})
.then((res) => res.json()).then((responseData) => {
console.log(responseData);
return responseData;
})
}
file where you call function
graphql()
.then((e) => {
console.log("data", e)
});
I have this function in JS:
export let findUser = (user, pass) => fetch(baseURL+'/api/Login',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username:user,
password:pass,
})
})
.then((response) => response.json())
.then((res) => {
if(res.success === true){
return 'A';
}else{
alert(res.message);
}
}).
.done();
But when I call it in React like this :
var user = file.findUser(this.state.username,this.state.password);
I got undefined as content of variable user, How can I pass a value from the first function and get it in react native ?
I would suggest exporting the initial method call and handling the .then() and .done() within the area being exported to. For example:
I have this function in JS:
export let findUser = (user, pass) => fetch(baseURL+'/api/Login',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username:user,
password:pass,
})
})
using in another file
let user // assign user within response block
file.findUser(this.state.username, this.state.password)
.then((res) => { /* do what you want */ })
.then((res) => { /* do what you want */ })
.done()