React native 'Cannot read property of undefined' AsyncStorage - javascript

I try to load the ID from a ble device via AsyncStorage that I save in a another component. But then I do this I get the following error:
ExceptionsManager.js:65 Cannot read property 'loadMac' of undefined
This is my loadMac() function:
export function loadMac() {
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item);
return item;
})
.catch((error) => {
console.log(error);
});
}
And I call this function in my component like this:
store.loadMac();
Then I try
AsyncStorage.getItem(MAC_KEY)
.then((item) => {
console.log(item)});
I will get my ID.. but not from my function that I have in another file.
Any solution ?

The error message says store is not defined, so you should look for a solution checking it.
By the code you posted I am assuming you've tried to have 2 different components: one stateless component named 'store' which you are exporting to access its' loadMac function. And another where you are importing the 'store' component. Correct me if I'm wrong.
If this is the case, your export syntax is incorrect. It should be something similar to this
export default const Store = () => {...}
And then import it like this:
import Store from './yourPathToStore';
If it's not, then you shouldn't have that export and also clarify what is exactly your 'store'.
Hope it helps.

Related

React Restful api is making problem with json

I have been trying all sort of things but this is first time this happens. I spend days on google and youtube to find something but nothing works nor one opinion nor many all together or some kind of combinations.
import React, { Component } from "react";
class App extends Component {
componentDidMount() {
fetch("../public/data.json")
.then(res => res.json())
.then(data =>
console.log(data);
);
}
render() {
return <div></div>;
}
}
export default App;
And the error is:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
If you want to get data from a local json file you don't need to use fetch method. You can simply import your file.
You thus don't need to use fetch method in your componentDidMount. In the future if you want to use fetch method you have to remember that fetch takes an url. I provide you a valid url to show you an example.
import React, { Component } from "react";
import json from "../public/data.json";
class App extends Component {
componentDidMount() {
fetch("https://randomuser.me/api/?results=10")
.then(res => res.json())
.then(data =>
console.log(data);
);
console.log(json); // print your Json file
}
render() {
return <div></div>;
}
}
export default App;
You are giving your fetch call a relative path to a file. This needs to be your API endpoint.
componentDidMount() {
fetch("../public/data.json") // this needs to be a url
.then(res => res.json())
.then(data =>
console.log(data);
);
}
if you have the JSON file locally already and just want your React Component to have access to it, then just import it import jsonData from "../public/data.json"
You can simply use 'require' to import your JSON file, if it is local.
E.g.: const data = require('../public/data.json'). console.log(data) will return the entire JSON object.
Edit: One thing to remember is that require() will always cache the content of the loaded module (or file, in this case). The next time require() is called again, it will restore it from the cache instead of reading it again.
On a contrary with other answers, fetch("../public/data.json") is a valid url. The only problem is that it will take current url in the browser, go one level up (e.g. remove content after last /) and append public/data.json, then try to fetch the resource. So the error Unexpected token < in JSON at position 0 comes from trying to parse html (most likely <!doctype html> as json

Access Vuex in asyncData function

I want to access my Vuex data in asyncData but I can't. Also I can't seem to be able to use axios module in asyncData.
I tried a lot.
pages/index.vue
export default {
asyncData() {
//in my project there's a lot more code here but i think this is enough
let id = this.$store.state.id //i know i should prob use getter but no
//here i want to do an axios req with this var "id" but axios doesnt work
return axios.get(`url${id}`)
.then(...) //not gonna write it out here
}
}
store/index.js
export const const = () => ({
id: "#5nkI12_fSDAol/_Qa?f"
})
I expect it to get the ID from Vuex and then do a Axios req. Whole app doesn't work.
The context provides additional objects/params from Nuxt to Vue
components. The context is available in special Nuxt lifecycle areas
like asyncData, fetch, plugins, middleware, modules, and
nuxtServerInit.
Reference
export default {
asyncData({ store }) {
const id = store.state.id
return axios.get(`url${id}`)
.then(...)
}
}

Making global functions to access vuex store

so I want to make a global function that I can access in every component of mine. So I stumbled upon Vue Plugins. They worked great, till I tried out my use case. I need to use some information from the vuex store in my plugin and return a true or false value.
So this is what I have tried
plugin.js
export default {
install (Vue) {
Vue.prototype.$rbac = (method, route) => {
$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route==route)
}
}
}
main.js
import plugin from './utils/common/plugin'
...
Vue.use(plugin)
...
component.vue
<template>
...
<div v-if="$plug('post', '/project')></div>
...
</template>
But I get an error saying "ReferenceError: $store is not defined".
It kind of makes sense that I cannot access the store. The store only gets the value once the user logs in.
So is there any way I can make a global function that can access the store when it gets values?
You're getting the reference error because the $store variable hasn't been defined anywhere. It's not a local variable, nor is it a function parameter or global variable.
You probably meant to do this.$store; also make sure you use function () {} syntax and not () => {} because you don't want to bind this.
export default {
install(Vue) {
Vue.prototype.$rbac = function (method, route) {
this.$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route == route)
}
}
}
You could also use a global mixin to do a similar thing instead of a plugin.

Issue with Reactjs Facebook login library - Make componentClicked function asynchronous

I am trying to implement facebook login for my react app (with redux).
The component "FacebookLogIn" in my loginUser.js file looks like this:
<FacebookLogin
appId="375026166397978"
autoLoad={true}
fields="name,email,picture"
onClick={this.componentClicked.bind(this)}
callback={this.responseFacebook} />
So when I try to import an action like this:
import { loginWithFaceBook } from '../actions/';
And try to login with facebook through the componentClicked function:
componentClicked(){
console.log(this.props);
this.props.loginWithFaceBook(facebookUser);
}
I got an error
bundle.js:51161 Uncaught TypeError: this.props.loginWithFaceBook is not a function
I think this is scope issue since I also import a normal login function from 'actions' folder as {login}, and this.props.login works as normal, but I don't know how to fix it.
I fixed the issue by removing this.props. So how would I make this function an asynchronous function, I tried chaining the then callbacks but it does not work ?
componentClicked(){
loginWithFaceBook(facebookUser).then(() => {
this.props.history.push('/posts');
}).catch((e) => {
alert(e);
});;
}
The error is:
bundle.js:51165 Uncaught TypeError: (0 , _actions.loginWithFaceBook)(...).then is not a function
I would really appreciate any help.
Change
this.props.loginWithFaceBook(facebookUser);
to
loginWithFaceBook(facebookUser);
As you are importing
import { loginWithFaceBook } from '../actions/';
you don't need to use this.props you can directly use it. this.props comes to picture when you want to use parent's props.

React - Can't call function in api file for pokedex app

i'm building a pokedex (pokemon index) using an api called pokeapi. I decided to use this wrapper to make things a little easier: https://github.com/PokeAPI/pokedex-promise-v2
I have a input field and when the submit button is clicked, I want the api to return the pokemon if there is a match.
Searchbar.js:
onClick() {
var text = this.state.text;
PokeApi.getPokemon(text).then(function(data) {
console.log(data);
}.bind(this));
}
api.js:
import React, { Component } from 'react';
import Pokedex from 'pokedex-promise-v2';
var P = new Pokedex();
var PokeApi = {
getPokemon: function(query) {
P.getPokemonByName(query)
.then(function(response) {
return response;
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
}
}
export default Component
Now when I click on submit, I get the following in console:
Uncaught TypeError: _api2.default.getPokemon is not a function
I can't seem to figure out what '_api2.default' is or how to get pass this issue. If anyone could provide some assistance it would be greatly appreciated, thanks!
Your code sample doesn't appear to be complete but you probably need to export the PokeApi object and import it where you plan to use it.
(Perhaps you intended to export PokeApi from api.js rather than re-exporting React.Component?)
We use Pokeapi for get all data about Pokemon.
Here is list of all Pokemon.
http://pokemongotech.com/pokemongo-pokedex-newswoof1orderbyid?swoof=1&orderby=id

Categories

Resources