set mobx store in const value in react native - react-native

how can i set const value using mobx obeserve data? as i don't know how can i define props here.
export const BASE_URL = base_url_from_mobx
i have some data in this function. From there i will have some confidential data and a base url. This ApiKeys is a native module
ApiKeys.getApiKeys((data)=>{
let secureData = JSON.parse(data)
}
i have an api.js file where i set the interceptor and set the base url like below
const api = axios.create({
baseURL: BASE_URL,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
here BASE_URL is defined and export as const in constants.js file but now i want to set it from the value i have got from the function.
This can be done if i can do like below
const api = axios.create({
// baseURL: BASE_URL,
baseURL: (JSON.parse(AsyncStorage.getItem(SECURE_KEY))).SOHOJ_APP_API_BASE_URL_DEVELOPMENT,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
but it is giving me issue like
how can i do that. my i use to make a request like below using api.js
api
.post('api_end_point',parameters,headers)
.then(response=>{
})
.catch(error =>{
})
thanks

It means that there is some issue with your AsyncStorage.getItem(SECURE_KEY) ,probably it's not a proper json object.do a console.log of AsyncStorage.getItem(SECURE_KEY) and see what value you get.

Related

Vuejs axios get request always fetch new values [duplicate]

I am trying to query a quote API for a freeCodeCamp project I'm updating to React.js. I am now trying to use Fetch or Axios to query the API but it's caching the response in the browser. I know in $ajax there is a { cache: false } that would force the browser to do a new request.
Is there some way I will be able to do the same with Fetch or Axios?
The cache-control setting seems to be already set to max-age: 0 by Axios.
This is my code I have that is querying the API.
generateQuote = () => {
axios.get('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1')
.then(response => {
const { title, content, link } = response.data[0];
console.log(title, content, link)
this.setState(() => ({ title, content, link }));
})
.catch(err => {
console.log(`${err} whilst contacting the quote API.`)
})
}
Okay so I found a solution. I had to set a timestamp on the API url to get it to make a new call. There doesn't seem to be a way to force axios or fetch to disable cache.
This is how my code now looks
axios.get(`https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp=${new Date().getTime()}`)
.then(response => {
const { title, content, link } = response.data[0];
console.log(title, content, link)
this.setState(() => ({ title, content, link }));
})
.catch(err => {
console.log(`${err} whilst contacting the quote API.`)
})
I added these headers to all axios requests and it's working well.
axiosInstance.defaults.headers = {
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': '0',
};
If you do not want to disable caching for all axios requests, you can disable caching for only one request by using the following parameters in the axios call:
axios.get(
'https://YOUR-URL.com',
{
// query URL without using browser cache
headers: {
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Expires': '0',
},
}
)
It seems, adding timestamp is the only always working way.
If you're using Vue, for example:
const api = axios.create({
baseURL: 'https://example.com/api',
params: {
t: new Date().getTime()
}
})
Vue.prototype.$api = api
So you can use it with:
this.$api.get('items')
And it will always add different timestamp to the url, depending on current request time.
I think you just need to make the url different each time you make the axios call. Timestamp is just one way to do so. Also consider disabling or filtering service workers caching method if you are developing a PWA.
Create an instance of axios and then add timestamp to every request.
const axiosInstance = axios.create({})
axiosInstance.interceptors.request.use(
function (config) {
// Do something before request is sent
config.params = { ...config.params, timestamp: Date.now() };
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);

NuxtJS - manage several axios instances

I use NuxtJS 2, and I need to have 2 or more axios instances with different configs.
In VueJS / JS classic, I can just create a new instance of axios:
var axiosElasticSearch = axios.create({
baseURL: 'https://elastic.com/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
But in Nuxt, they apply their own config to handle this, because of the SSR layer.
In my Nuxt config, I have this :
axios: {
baseUrl: process.env.API_URL,
browserBaseUrl: process.env.BROWSER_API_URL,
withCredentials: true,
headers: {
common: {
Accept: 'application/json',
Authorization: 'Bearer ' + process.env.API_TOKEN
}
}
},
And then, I can inject it easily.
Is it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.
nuxt/axios allows creating new Axios instances with $axios.create, which takes the Axios config from nuxt.config.js into account.
For example, you could create a Nuxt plugin that injects a new Axios instance into the root context:
// ~/plugin/api.js
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*'
}
}
})
// Set baseURL to something different
api.setBaseURL('https://my_api.com')
// Inject to context as $api
inject('api', api)
}
And configure your Nuxt app to use it:
// nuxt.config.js
export default {
plugins: ['~/plugins/api.js']
}
Then your component could use the new Axios instance:
// MyComponent.vue
export default {
fetch() {
this.$api.get(...)
},
asyncData({ $api }) {
$api.get(...)
}
}

How to solve Cannot read property 'defaults' of undefined in vue?

I am setting default headers in my vue application, but when I load the app it show me error.
main.js?56d7:14 Uncaught TypeError: Cannot read property 'defaults' of undefined
Code
const token = sessionStorage.getItem("token");
if (token) {
Vue.prototype.$http.defaults.header.common["Authorization"] = token;
}
I made a working codepen based on your issue.
In your case, you need to create axios client.
Please check this codepen. https://codepen.io/endmaster0809/pen/VwaPGzr
let apiClient = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
const token = "testtoken";
if (token) {
apiClient.defaults.headers.common["Authorization"] = token;
}
Vue.prototype.$http = apiClient;

Put API KEY in axios

I just started learn React but I have problem when I trying to make a request to the CoinMarketCap API with axios and tried several ways to set my API key. I have also also tried on Postman but message appears API key missing.
export const apiBaseURL = 'https://pro.coinmarketcap.com';
Tried like this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`,
{ headers =
{ 'X-CMC_PRO_API_KEY': 'apicode', }
})
this
dispatch({ type: FETCHING_COIN_DATA })
let config = { 'X-CMC_PRO_API_KEY': 'apicode' };
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`, { headers: config })
and this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?X-CMC_PRO_API_KEY=apicode`)
Thank you
The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
Adding the key to the default headers was the only way I could get this to work.
Use CMC_PRO_API_KEY as a query parameter, instead of X-CMC_PRO_API_KEY:
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?CMC_PRO_API_KEY=apicode`)
I realize this has been solved; for the sake of alternatives here is how I did it. I created a instance of axios in /includes/axios:
import axios from "axios";
const instance = axios.create({
baseURL: "https://example.com/api",
headers: {
"Content-Type": "application/json",
"x-api-key": "****API_KEY_HERE****",
},
});
export default instance;
Now axios can be imported anywhere in the project with the give configuration. Ideally you want to add your secret to the ENV variable for security reasons.

Config Axios globally with Authenticated in NuxtJS - VueJS

I finding way to config Axios globally with Authenticated in NuxtJS - VueJS (I use mainly NUXTJS).
All I need is: If user logged in and have token in $store, axios will get this token. If user is anonymous, axios wont get this token
~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'JWT ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
~/store/index.js
const AuthenticationStore = () => {
return new Vuex.Store({
state: {
token: null
},
mutations: {
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
},
actions: {
....
}
})
}
export default AuthenticationStore
Error: [nuxt] Error while initializing app TypeError: Cannot read property 'token' of undefined
I would suggest to use interceptor instead which is more flexible and getting token when making request not on creation. Try something like that to avoid issues with not set token.
// ~/plugins/axios
import axios from 'axios'
import AuthenticationStore from '~/store'
var api = axios.create({
baseURL: 'http://localhost:8000/api/v1/',
'headers': {'Authorization': 'JWT ' + AuthenticationStore.state.token}
})
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': AuthenticationStore.state.token ? 'Bearer ' + AuthenticationStore.state.token : ''
}
return config
}, function (error) {
// Do something with request error
return Promise.reject(error)
})
export default api
If you need to have no auth header, you need to add if at the begging of the interceptor.
Issue with your store:
You are exporting function when you should export instance of store,
so this is wrong:
const AuthenticationStore = () => {
You should export instance so:
const AuthenticationStore = new Vuex.Store({ ...
Please visit https://vuex.vuejs.org/guide/ to get better understanding. It is not bad that you don't understand it fully! Modules/instances/exporting in JS is not really easy to understand fully. Just try to learn it more. Good luck.