Is it possible somehow to integrate youtube data API v3 directly in react-native?
If not, Is there any other way to do it?
Right now I am using axios to send get request but not able to figure out how exactly send the request what I tried is this:
componentWillMount() {
axios.get('https://www.googleapis.com/youtube/v3/channels', {
params: {
'id': 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'key': 'AIzaSy...',
'part': 'snippet,contentDetails,statistics'
}
}).then(
(response) => {
console.warn(response);
}).catch(
(error) => {
console.error(error);
});
}
Not sure whether it is correct or not as I don't have much experience in React native. Any help would be appreciated.
You could probably use packages like youtube-search or youtube-api-searchfor your purpose.
The call with the latter one looks like this:
import YTSearch from 'youtube-api-search';
YTSearch({ key: YOUR_API_KEY, term: YOUR_SEARCH_STRING }, result => {
console.log(result);
});
Related
I am trying to fetch products by 'SKU', which is only possible using Admin API. I need to inject a JavaScript code snippet into theme.liquid file. Can I achieve this via JavaScript only? So far my code looks something like this:
<script>
const query = `{
productVariants(first: 1, query: "sku:<SKU>") {
edges {
node {
id
price
product {
title
description
featuredImage {
id
originalSrc
}
}
}
}
}
}`;
const STOREFRONT_ACCESS_TOKEN = 'xxxxxxxxxx';
const GRAPHQL_URL = 'https://<my-store>.myshopify.com/admin/api/2021-01/graphql.json';
const GRAPHQL_BODY = {
'method': 'POST',
'headers': {
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
'Content-Type': 'application/json',
},
'body': JSON.stringify({ query })
}
fetch(GRAPHQL_URL, GRAPHQL_BODY)
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
</script>
I am not very well familiar with Shopify and Shopify's APIs(Storefront, Admin). I tried every possible way but reached dead end. I would really appreciate if someone can redirect me to right resources. Thank you!
Your code looks loosely like the code from the docs here: https://shopify.dev/tutorials/authenticate-with-oauth
Two issues, really:
in this line:
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
you need be using a token which you get after you request it from
https://{shop}.myshopify.com/admin/oauth/access_token
the bigger issue, though, is:
to do so only through the theme code, you would ultimately have to expose your secret keys via the front end code, which is going to be a security risk. The technically correct way to use the Admin API would either be to set up a server that runs an embedded app and store those keys in a .env file there.
AsyncStorage.getItem('token').then(value => {
token = value
console.log("Assigned token")
});
What is the proper way to read this synchronously?
I tried using await/async, they weren't installed, and have tried several ways to install babel generators.
How do I install async/await in React Native and read synchronously?
You don't need to install async/await. It's already there. To use, this is the way it should be. Declare the function as async then put await before AsyncStorage.
async Some(){
var token = await AsyncStorage.getItem('token')
console.log("Assigned token:",token)
});
}
Actually I think you are fine without await/async. You are just sending the "problem" of handling the promise to the parent function.
Usually, what I do, (if you are thinking about loading the auth token before continuing) is something like:
this.setState({loading: true}, () => {
AsyncStorage.getItem('token').then(value => {
token = value
console.log("Assigned token")
this.setState({loading: false}, () => {
this.continue();
})
});
})
I am trying to access a prestashop API with vuejs2
<script>
import axios from 'axios'
export default {
data () {
return {
get: [],
errors: []
}
},
created () {
axios({
method: 'get',
url: 'https://myprestashopsite.com/api/categories/?ws_key=J***************Z&filter[id_parent]=5&output_format=JSON'
}).then(response => {
this.get = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
In the web developer console of mozilla I see that my request return a 200 with the data in the response. But I get "Error: Network Error app.js%20line%201266%20%3E%20eval:15:15" catch as an error.
I tried with another API and it worked, so I guess it comes from the prestashop api. (prestashop version 1.7.3.0)
Is there a way to fix this ?
The problem seems to come from axios. I had to add a rule to the server.
I found the solution to this on this thread :
https://github.com/axios/axios/issues/853
There are other solutions I didn't try in this thread if mine doesn't work.
how to add the rule : https://enable-cors.org/server.html
In this article, it says:
While it’s generally poor practice, you can use Axios directly in your components to fetch data from a method, lifecycle hook, or whenever.
I am wondering why? I usually use lifecycle hooks a lot to fetch data (especially from created()). Where should we write the request calls?
Writing API methods directly in components increases code lines and make difficult to read.
As far as I believe the author is suggesting to separate API methods into a Service.
Let's take a case where you have to fetch top posts and operate on data. If you do that in component it is not re-usable, you have to duplicate it in other components where ever you want to use it.
export default {
data: () => ({
top: [],
errors: []
}),
// Fetches posts when the component is created.
created() {
axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
.then(response => {
// flattening the response
this.top = response.data.map(item => {
title: item.title,
timestamp: item.timestamp,
author: item.author
})
})
.catch(e => {
this.errors.push(e)
})
}
}
So when you need to fetch top post in another component you have to duplicate the code.
Now let's put API methods in a Service.
api.js file
const fetchTopPosts = function() {
return axios.get(`http://jsonplaceholder.typicode.com/posts/top`)
.then(response => {
// flattening the response
this.top = response.data.map(item => {
title: item.title,
timestamp: item.timestamp,
author: item.author
})
}) // you can also make a chain.
}
export default {
fetchTopPosts: fetchTopPosts
}
So you use the above API methods in any components you wish.
After this:
import API from 'path_to_api.js_file'
export default {
data: () => ({
top: [],
errors: []
}),
// Fetches posts when the component is created.
created() {
API.fetchTopPosts().then(top => {
this.top = top
})
.catch(e => {
this.errors.push(e)
})
}
}
It's fine for small apps or widgets, but in a real SPA, it's better to abstract away your API into its own module, and if you use vuex, to use actions to call that api module.
Your component should not be concerned with how and from where its data is coming. The component is responsible for UI, not AJAX.
import api from './api.js'
created() {
api.getUsers().then( users => {
this.users = users
})
}
// vs.
created() {
axios.get('/users').then({ data }=> {
this.users = data
})
}
In the above example, your "axios-free" code is not really much shorter, but imagine what you could potentially keep out of the component:
handling HTTP errors, e.g. retrying
pre-formatting data from the server so it fits your component
header configuration (content-type, access token ...)
creating FormData for POSTing e.g. image files
the list can get long. all of that doesn't belong into the component because it has nothing to do with the view. The view only needs the resulting data or error message.
It also means that you can test your components and api independently.
I am using react-native, redux-thunk, jwt and AsyncStorage to authenticate and locate user in this project. It seems that the request goes to backend from the axios, but I do not see the response back ('in axios' and '?' are not displayed) in the chrome console and I have no idea what possibly goes wrong in my code.
in my actions/userAuth.js
import { AsyncStorage } from 'react-native';
import axios from 'axios';
export function updateUserLoc(username, lat, lng) {
return function(dispatch) {
AsyncStorage.getItem('token').then(function(token) {
console.log('out');
axios.put(`${ROOT_URL}/:${username}/location`, {location: [lat, lng], token})
.then((response) => {
console.log('in axios');
// console.log('update user location', response);
dispatch({
type: USER_LOC_UPDATE
});
console.log('?');
})
.catch(err => { console.log('user location err', err); });
})
.catch(err => { console.log('Async Storage err', err)});
}
}
has anyone had this kind of problem before or does anybody know what the problem is in this code and how to debug it?
will appreciate any kind of advice or answer.
Thank you.
I don't think AsyncStorage.getItem returns a Promise. According to the docs, getItem takes an optional second param that is your callback function. Alternatively you can use async/await if you have ES7 support.