mern api route with axios - api

we are making an app using mern that will populate the page with what ever wine you search for. But i cant get my api route to work.
loadWines = () => {
Axios.get("https://services.wine.com/?t=" + wineName + "&y=&apikey=05bd3e5306d43d741a06a939c5ea3dd27eaad377" + this.state.value)
.then(res=>res.json())
.then(json => {
this.setState({
value: '',
isLoaded:true,
Wines:json,
})
});
}
handleChange(event) {
this.setState ({value: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
Axios.get("https://services.wine.com/?t=" + wineName + "&y=&apikey=05bd3e5306d43d741a06a939c5ea3dd27eaad377" + this.state.value)
.then(res=>res.json())
.then(json => {
this.setState({
value: '',
isLoaded:true,
Wines:json,
})
});
console.log(this.state.value)
}

Actually I think axios does returns json data, no need to convert to JSON,
fetch method does returns promise then we definitely need to convert it into res.json()
try this:
import axios from 'axios';
function(){
axios.get(url).then(res=>{
this.setState({data: res})
})
}
let me know there is anything more. Happy coding

Related

Pass data from one API to another using Vue.js

I am making an API call to return a list of appointments. Each appointment has a clientID as a FK so that we can get client information. Is it possible to get that clientID when I make the call to the appointments API and use the clientID to make a call to a client using ID. Here is what I was thinking of how it might work but it is not working. Also an explanation of why this doesnt work would be nice.
export default{
data (){
return{
appointment: [],
client: []
}
},
created() {
axios.get("http://localhost:3000/api/appointment")
.then(res => this.appointment= res.data)
.catch(err => {
console.log(err)
}),
axios.get("http://localhost:3000/api/client/" + this.appointment.clientID)
.then(res => this.client = res.data)
.catch(err => {
console.log(err)
})
}
It does not work, beacause both axios calls are made simultanisously.
clientID is not defined, when you make the second axios call
Make sure the first call is done before using data from that response.
axios.get(...)
.then(response => {
this.appointment = response.data
axios.get(".../" + response.data.clientID)
.then(response => this.client = response.data
})
.catch(e => console.log(e))

Pass Response Value in Vue Component

i already call the axios and show using console log if it is successful or not already, However i wanted to pass the axios post response value to my vue component and display the response in my vue component in order for me to make a condition. Is there any way to do it? I try some other part but no luck. Kindly guide me.
main.vue
methods: {
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then(() => {
alert("Success");
})
.catch(() => {
alert("Error");
})
}
}
clicked.js
return new Promise((resolve, reject) => {
clicked(username, password)
.then(resp => {
console.log("---->>>> : ");
const data = resp.data.data
console.log(username, password);
console.log(resp);
console.log("statresponse.status : " + resp.data.status);
console.log("statresponse.message : " + resp.data.message);
console.log("statresponse.inside message : " + resp.data.data.message);
// console.log("USER.JS RESPONSE: " + resp.data.status);
// console.log("USER.JS RESPONSE: " + resp.data.message);
setToken(data.token)
commit('SET_TOKEN', data.token)
resolve()
})
.catch(error => {
console.log(error)
reject(error)
})
})
Try changing main.vue to:
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then((response) => {
//Do whatever you want with your response
alert("Success");
})
.catch(() => {
alert("Error");
})
}
and change clicked.js to:
resolve(resp.data.data)
This will make so the promise resolves the response data.
However if you make the http request in your store/using vuex, what you probably want to do is commit a mutation to put the response into your state - and then map the state from your component.

React Native fetch doesn't work in another fetch callback

If I call my api function from POINT 1, fetch method inside the api method works well. When I comment it out and call the function at POINT 2 fetch method inside the addAccount() doesn't work. There is no exception, no rejection, no request on Reactotron, even I can't find request over Charles Proxy. What is the difference and what I have to know to figure it out?
I tried with RN 0.55.2 and 0.57.5
// Auth.js typical react native component
import * as api from '../actions/api';
class Auth extends Component {
// first triggered function
loginAccount(){
// api.addAccount(); // POINT 1 - this line works well if I uncomment
fetch('https://domain-a.com/login/',{
method: 'POST',
credentials: "same-origin",
headers: {
'accept-language': 'en-US;q=1',
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: encodeURIComponent(bodyParameters)
}).then((response) => {
console.log(response);
return response.json()
}).then(({ status, invalid_credentials }) => {
if(status == "ok"){
CookieManager.get('https://domain-a.com')
.then((cookies) => {
this.fetchAccountData(cookies);
})
})
}
fetchAccountData(cookies){
fetch('https://domain-a.com/'+cookies.user_id+'/info/',{
method: 'GET',
headers: {
'cookie': cookies
}
}).then((response) => {
return response.json();
})
.then(({ user, status }) => {
api.addAccount(); // POINT 2 - this line doesn't work
});
}
}
// api.js
// I repleaced fetch code with document example just to be clearify
export const addAccount = () => {
console.log("fetch begin"); // always works
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); // won't works from point 2
})
.catch((error) =>{
console.error(error); // never runs
});
}
It looks like your first .then statement in the addAccount() function is missing a return statement. responseJson would be undefined without a proper a 'return response.json()' statement. Also adding brackets for better semantic formatting.
export const addAccount = () => {
console.log("fetch begin"); // always works
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => {
console.log(response); //test this response
return response.json();
})
.then((responseJson) => {
console.log(responseJson); // won't works from point 2
})
.catch((error) =>{
console.error(error); // never runs
});
}

Fetch someUrl.html not working in React Native / Expo?

I'm trying to use fetch to get the contents of the HTML page in React Native, and I'm running it on expo, here:
https://snack.expo.io/#abalja/hellofetch
Basically the code is nothing special, uses 'fetch' which does work for loading .json files, but I can't get it to work for .html files. It just silently fails, and I don't even get an error logged. I'm not sure if this is Expo or ReactNative issue.
const url2 = 'http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html#ref=rss'
export default class App extends React.Component {
componentDidMount(){
console.log('did mount, fetching: ' + url2)
fetch(url2)
.then((response) => {
console.log(response) // 1
return response.text()
})
.then((responseText) => {
console.log('fetch text', responseText) // 2
// return responseText.movies;
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.container}>
</View>
);
}
}
At 1 I get the response logged:
{type:"default",status:200,ok:true,headers:{…},url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html",_bodyInit:{…},_bodyBlob:{…}}
type:"default"
status:200
ok:true
►headers:{map:{…}}
url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html"
►_bodyInit:{_data:{…}}
►_bodyBlob:{_data:{…}}
At 2 I get absolutely nothing logged.
Promise syntax is confusing to me, so I changed into async-await:
async componentDidMount() {
console.log('did mount, fetching: ' + url2);
try {
let response = await fetch(url2);
let text = await response.text();
console.log(text)
} catch(e) {
console.log(e)
}
}
It works! You can check it here: https://snack.expo.io/#aazwar/fetch-url
It's because you are parsing your Response as text and not as json, and then trying to call object-key against string. Basically what you have at that point is string which looks like json. Parse your response with .json()-method instead.
return response.text() should be therefore return response.json()
to reconstruct your code
// With .then()
fetch(url2)
.then((response) => {
return response.json()
})
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
// OR with await/async
const response = await fetch(url2)
const json = await response.json() // As '.json()' is async function as well
return json.movies
I would succest using await/async since syntax is much more cleaner and it start's to be way to go.

Vuejs axios count results after they have been returned

I'm trying to find the correct way to get the number of returned results from my async axios get query but not getting anywhere so hoping someone can assist
My code is as follows
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
countResults(response) //this doesn't seem to
.catch(error => console.log(error))
})
},
filters:{
countResults: function(value){
return value.length;
}
I then call as follows
<p>Number of Entries: {{countResults}}</p>
Thanks
You can call the filter method in this way
this.$options.filters.countResults(response)
To solve your problem you need to store the response. You can do that in this way
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
this.responseData = response.data
}).catch(error => console.log(error))
},
data: {
responseData: []
},
filters: {
countResults: function(){
return this.responseData.length;
}