Determine if Axios request is done - json

Is there any way to determine if a Axios request like the following received an answer and is done?
axios.get('/api')
.then(response => this.data = response.data);

Yes, this is a promise and you can reference and then it:
var req = axios.get('/api')
.then(response => this.data = response.data);
Now I want to react to it being done:
req.then(x => console.log("Done!"));
Or save that state outside:
var isReqDone = false;
req.then(x => isReqDone = true);

Related

how to get data from fetch to a variable?

so i'm fetching this api using the fetch
fetch("https://public-api.solscan.io/transaction/"+JSON.parse(message.data).params.result.value.signature)
.then(response => response.json())
.then(response => console.log(JSON.stringify(response.parsedInstruction[1].params.mint)))
.catch(error => nothing());
but i need
JSON.stringify(response.parsedInstruction[1].params.mint
in a variable so i can make another api request please help me
this is the code where i want to use with the variable
const mintAddress = new PublicKey("7brV5ykCzriKhVhj99kav97LQQrpb18J3kMonGxveML2");
const nft = await metaplex.nfts().findByMint({ mintAddress }).run();
const png = nft.json.image ;
console.log(nft.json)

How to print json api data in reactjs

I'm fetching json api details through GET request and trying to print it. Getting an error:
Error in the console is Uncaught ReferenceError: allUsers is not defined
const Dashboard = ({status, juser}) => {
const [allUsers, setAllUsers] = React.useState([]);
const id = juser.actable_id;
console.log(id); //getting id here as 1
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
console.log(response.data);
setAllUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
React.useEffect(() => {
getAllusers();
}, []);
{allUsers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
}
export default Dashboard;
I'm new to react. Any help is appreciatable.
const [state, setState] = React.useState([]);
the state is where your data is located and setState is function to reset the state from anywhere,
so on your code,
const [jobseekers, allUsers] = React.useState([]); // change string to array
jobseekers is the variable where your data is located and allUsers is the function to store data into state.
set data to state using allUsers function,
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
allUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
and map from jobseekers
{jobseekers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
Also I would suggest to rename your state and setState as,
const [allUsers, setAllUsers] = React.useState([]);
You didn't pass the value of response to allUsers, instead, you just created a new variable. So change
const allUsers = response.data;
to:
allUsers(response.data)
Besides, you can also improve the way that you have used useState. You have initialized it as an empty string while you'll probably store an array from response in jobseekers. So, initialize it as an empty array.
const [jobseekers, allUsers] = React.useState([]);

Why is this promise returning an [object Promise] and not the value?

I thought I fully understood promises, but I'm stumped on this. I realize I should use async/await, but for this example I specifically want to only use .then().
When I do this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json() )
.then( data => {
console.log(data)
return data
});
the console.log(data) in the last function prints the JSON as expected, but when I try to console.log(theJson), the returned value, it prints [object Promise].. Why is this?
I was able to get the data outside of the function using react's useState/useEffect but not with just a vanilla global variable. I'm not trying to solve anything, but just want to understand why this does not work.
export default function App() {
let globalVar;
const [theQuote, setTheQuote] = useState({});
useEffect(() => {
fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`)
.then(quoteTypeResponse => quoteTypeResponse.json())
.then(quoteType =>
fetch(
'https://programming-quotes-api.herokuapp.com/quotes/' +
quoteType.type
)
)
.then(quoteResponse => {
return quoteResponse.json();
})
.then(quote => {
setTheQuote({ quote: quote.en, author: quote.author });
globalVar = quote.author;
});
}, []);
return (
<div id="app">
<h1>{theQuote.quote}</h1> // renders
<h2>{theQuote.author}</h2> // renders
<h3>globalVar: {globalVar}</h3> // undefined
</div>
);
}
Because your second .then() is inside the first then(), so theJson is a Promise<T>. The nice thing about Promise<T> is that you can move an inner .then() call up a level and it will still work:
Change it from this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json().then( data => {
console.log(data)
return data
} )
);
To this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json() )
.then( data => {
console.log(data)
return data
});
But ideally, use async function so you can have this considerably simpler code instead:
const resp = await fetch( `https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json` );
const data = await resp.json();
console.log( data );
#pushkin left a good link explaining the differences between async/await and using .then(), but basically, the value returned by the then() is only available within that block.
Promises cheat sheet: https://levelup.gitconnected.com/async-await-vs-promises-4fe98d11038f
fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`)
.then(quoteTypeResponse => quoteTypeResponse.json())
.then(quoteType =>
fetch(
'https://programming-quotes-api.herokuapp.com/quotes/' + quoteType.type
)
)
.then(quoteResponse => {
return quoteResponse.json();
})
.then(quote => {
console.log(`q:${util.inspect(quote)}`);
document.getElementById('app').innerHTML = quote.en;
});

Pulling Data from JSON with React-Native

What's wrong with this picture ? :-)
I'm trying to pull values from my wordpress JSON objects.
I must not be addressing them the correct/proper way with React-Native.
Can someone direct me as to how to form the correct console log statement ?
As it stands right now, the variable 'theMediaLink' is coming up 'undefined' in the console log. :-(
state={
data:[]
}
fetchData = async() => {
const response = await
//response
fetch('http://example.com/wp-json/wp/v2/posts/')
//posts
const posts = await response.json();
this.setState({data:posts});
const theMediaLink = `https://example.com/wp-json/wp/v2/media/` + `${this.state.data.featuredmedia}`;
console.log('theMediaLink_value: ', theMediaLink);
}
I should add that the fetch is retrieving data as I use it later on with a FLATLIST to pull the posts. My question is I must be misforming the call, but how ?
This is more an issue of understanding of React rather than React Native.
Try this:
fetchData = async () => {
const URL = 'http://example.com/wp-json/wp/v2/posts/'
const response = await fetch(URL)
const posts = await response.json();
return this.setState({ data : posts }, () => {
const { data } = this.state
const theMediaLink = `https://example.com/wp-json/wp/v2/media/${ data.featuredmedia }`;
console.log('theMediaLink_value: ', theMediaLink);
});
}
Since setState is asynchronous, you won't be able to see the state update right away, that's why the callback is for.
More info on how to setState asynchronously and use its value after right here

Angular2 Http.Post - How to view webapi response

I'm new to Angular2/Typescript and I'm writing my first web application.
I'm trying to call a webapi using POST, it works, if I intercept the call using FIDDLER I can see the Json response.
Now, how I can log in the browser console the json ouput?
The code is this:
code call
var s = this.myService.doSearch();
s.subscribe(
data=> this.data = data,
error => this.errorMessage = <any>error
);
console.log(s);
service method
doSearch() {
var url = this.baseUrl;
return this.http.get(url)
.map(response => response.json())
.catch(this.handleError);
}
My question is: how and where I can view and manage the Json Output ?
Thanks
You need to console.log it after the async code is finished:
var s = this.myService.doSearch();
s.subscribe(
data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
If you are debug or run your application in browser you can got to inspect and then move to the Network tab. In this tab select your POST Request and the go to the tab Response and voila there is your json Response
Edit:
To log all response data do this:
return this.http.get(url)
.map(res => res.json())
.subscribe(data => { console.log(data);})
.catch(this.handleError);
}
Try this this will print what you have in your returned observable .
var s = this.myService.doSearch();
s.subscribe(data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
Always remember If you want to get data from observable.you need to subscribe it.
you can't log it like this console.log(s); because s returns an observable. you should subscribe and refer those data inside the subscribe .