TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition') - expo

Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
App.js
import { StyleSheet, Text, View, StatusBar, PermissionsAndroid, Platform,} from 'react-native';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import DestinationSearch from './src/screens/DestinationSearch/DestinationSearch';
import SearchResults from './src/screens/SearchResults/SearchResults';
import { useEffect, useState } from 'react';
//import * as Location from 'expo-location';
import Geolocation, { getCurrentPosition } from 'react-native-geolocation-service';
navigator.geolocation = require('react-native-geolocation-service');
export default function App() {
const androidPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Uber App location Permission",
message:
"Uber App needs access to your location " +
"so you can take awesome rides.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location");
} else {
console.log("Location permission denied");
}
} catch (err) {
console.warn(err);
}
};
useEffect(() => {
if (androidPermission) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
}, [])
useEffect(() => {
if(Platform.OS == 'android') {
androidPermission()
} else{
//IOS
Geolocation.requestAuthorization();
}
}, [])
return (
<View>
{/* <HomeScreen /> */}
<DestinationSearch />
{/* <SearchResults /> */}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop:StatusBar.currentHeight
},
});
`
DestinationSearch.jsx
import { View, Text, StyleSheet, SafeAreaView, StatusBar } from 'react-native'
import React, {useEffect, useState,} from 'react'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import {GOOGLE_MAPS_APIKEY} from '#env'
import PlaceRow from './PlaceRows';
const DestinationSearch = () => {
const [originPlace,setOriginPlace] = useState(null)
const [destinationPlace, setDestinationPlace] = useState(null)
useEffect(() => {
console.log('useEffect is called')
if (originPlace && destinationPlace) {
console.warn('Redirect to results')
}
}, [originPlace, destinationPlace])
return (
<SafeAreaView>
<View style={styles.container}>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'From...'
listViewDisplayed = 'auto'
debounce = {400}
currentLocation = {true}
currentLocationLabel='Current location'
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
renderRow={(data)=> <PlaceRow data={data}/>}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
styles={{
container: styles.autocompleteContainer,
textInput: styles.textInput,
listView: styles.listView,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setOriginPlace({data, details})
console.log(currentLocation)
}}
/>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'To...'
listViewDisplayed = 'auto'
debounce = {400}
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
renderRow={(data)=> <PlaceRow data={data}/>}
styles={{
container: {
...styles.autocompleteContainer,
top: 70
},
textInput: styles.textInput,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setDestinationPlace({data, details})
}}
/>

Related

possible unhandled promise rejection_Expo Image Picker

I want to use Expo Image Picker, but I'm getting the following error.
'Console Warning : possible unhandled promise rejection (id : 0)'.
I already installed 'expo-image-picker'.
Here's the promise code, I don't see what's wrong here, any ideas?
import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Platform, StyleSheet, Text, View, Button,Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
export default function App() {
const [image,setImage] = useState(null);
useEffect(async () => {
if(Platform.OS !== 'web'){
const {status} = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted'){
alert('Permisson denied!')
}
}
}, []);
const PickImage = async() => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes : ImagePicker.mediaTypesOptions.All,
allowsEditing:true,
aspect:[4,3],
quality:1
})
console.log(result)
if(!result.cancelled ){
setImage(result.uri)
}
}
return (
<View style={styles.container}>
<Button title = "Choose Image" onPress = {PickImage}/>
{image && <Image source={{uri:image}} style = {{
width : 200,
height:200
}}/>}
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Assigning properties to mediatypes is incorrect.
Correction: mediaTypes:ImagePicker.MediaTypeOptions.All,

Button doesnt work after adding mobx-react-lite the code doesnt show any error but it doesnt work it displays the list but button inside doesnt work

So i set up mobx and the files show no error in visual studio code and the react client app compile just fine and it shows the list of Departments but there is also a button thats not working its set up all fine and the onClick event is all fine but it doesnt work I had problems with mobx because its greater than version 6 or idk its version so i had to add the construvtor to display the list
Department store
import {observable, action, makeObservable} from 'mobx';
import { createContext } from 'react';
import agent from '../api/agent';
import { IDepartment } from '../models/department';
class DepartmentStore {
#observable departments: IDepartment[] = [];
#observable selectedDepartment: IDepartment | undefined;
#observable loadingInitial = false;
#observable editMode =false;
constructor() {
// Just call it here
makeObservable(this);
}
#action loadDepartments= () => {
this.loadingInitial = true;
agent.Departments.list()
.then(departments => {
departments.forEach((department) => {
this.departments.push(department);
})
}).finally(() => this.loadingInitial = false);
};
#action selectDepartment = (id: string) => {
this.selectedDepartment = this.departments.find(d => d.id === id);
this.editMode = false;
}
}
export default createContext(new DepartmentStore());
so everything here shows no error below ill display the DepartmentList code where it contains the button thats now functioning
import { observer } from "mobx-react-lite";
import React, { SyntheticEvent, useContext } from "react";
import { Item, Button, Segment } from "semantic-ui-react";
import { IDepartment } from "../../../app/models/department";
import DepartmentStore from "../../../app/stores/departmentStore";
interface IProps {
deleteDepartment: (event: SyntheticEvent<HTMLButtonElement>,id: string) => void;
submitting: boolean;
target: string;
}
export const DepartmentList: React.FC<IProps> = ({
deleteDepartment,
submitting,
target
}) => {
const departmentStore = useContext(DepartmentStore);
const {departments, selectDepartment} = departmentStore;
return (
<Segment clearing>
<Item.Group divided>
{departments.map((department) => (
<Item key={department.id}>
<Item.Content style={{ display: "flex" }}>
<Item.Header style={{ width: "100%", marginTop: "1em" }}>
{department.name}
</Item.Header>
<Item.Extra>
<Button
name={department.id}
loading={target === department.id && submitting}
onClick={(e) => deleteDepartment(e, department.id)}
content="Delete"
color="red"
floated="right"
/>
<Button
onClick={() => selectDepartment(department.id)}
content="View"
color="blue"
floated="right"
/>
</Item.Extra>
</Item.Content>
</Item>
))}
</Item.Group>
</Segment>
);
};
export default observer(DepartmentList)
;

how can i POST data from ant design form into Django Backed?

i trying to post data from ant design React.js into Python Django rest frame work.
so I am using method OnFinish to send data, but its not working.
MY big problem is , i don't know how can i Introduction Data i want to send them data from Form , by using React-redux or something else way , so please Help me .
#react.js Form:
import React, { Component } from "react";
import {
Form,
Input,
Button,
PageHeader,
Select,
DatePicker,
message,
} from "antd";
import "antd/dist/antd.css";
import { connect } from "react-redux";
import axios from "axios";
// defualt setting for django
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken";
// from layout setting
const formItemLayout = {
labelCol: {
xs: {
span: 24,
},
sm: {
span: 8,
},
},
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
// end fform layout setting
// const onFinish = (values) => {
// console.log(values);
// axios.post("http://127.0.0.1:8000/api/create/", {
// title: values.title,
// manager: values.manager,
// });
// };
// const title = event.target.elements.title.value;
// const manager = event.target.elements.manager.value;
class ExtrashiftForm extends React.Component {
constructor(props) {
super(props);
this.state = {
Extrashifts: [],
};
}
// componentDidMount() {
// this.fetchExtrashift();
// }
handleSubmit = () => {
axios
.post("http://127.0.0.1:8000/api/create", {
data: {
title: this.target.elements.title.value,
manager: this.data.item.manager,
},
})
.then((res) => {
if (res.status == 200) message.success("data successfully updated!");
this.fetchExtrashift();
})
.catch((err) => {
message.error("data profile failed to update ...");
});
};
render() {
return (
<div>
<Form {...formItemLayout} name="update">
<Form.Item label="Title :">
<Input name="title" placeholder="Put a title here" />
</Form.Item>
<Form.Item label="Manager :">
<Input name="manager" placeholder="Enter manager name" />
</Form.Item>
<Form.Item {...tailFormItemLayout}>
<Button
type="primary"
htmlType="submit"
onFinish={this.handleSubmit}
>
create
</Button>
</Form.Item>
</Form>
</div>
);
}
}
export default ExtrashiftForm;
#back end api/urls.py :
from Extrashift.api.views import ExtrashiftViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'', ExtrashiftViewSet, basename='Extrashift')
urlpatterns = router.urls
#backend : api/views.py:
from rest_framework import viewsets
from Extrashift.models import Extrashift
from .Serializers import ExtrashiftSerializers
class ExtrashiftViewSet(viewsets.ModelViewSet):
serializer_class = ExtrashiftSerializers
queryset = Extrashift.objects.all()
from rest_framework import permissions
from rest_framework.generics import (
ListAPIView,
RetrieveAPIView,
CreateAPIView,
UpdateAPIView,
DestroyAPIView
)
from my back end everything is work but Please help me to i can send only one data from this form.
if is possible please ,change my Code to the Correct code
Nothing spectacular here, you can read the docs
Rather than giving the name as a prop to the Input field.
I've passed it as a prop to Form.Item component
You can check the example here
import React, { Component } from "react";
import {
Form,
Input,
Button,
PageHeader,
Select,
DatePicker,
message,
} from "antd";
import "antd/dist/antd.css";
import axios from "axios";
// defualt setting for django
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken";
// from layout setting
const formItemLayout = {
labelCol: {
xs: {
span: 24,
},
sm: {
span: 8,
},
},
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
// end fform layout setting
// const onFinish = (values) => {
// console.log(values);
// axios.post("http://127.0.0.1:8000/api/create/", {
// title: values.title,
// manager: values.manager,
// });
// };
// const title = event.target.elements.title.value;
// const manager = event.target.elements.manager.value;
export default class ExtrashiftForm extends React.Component {
constructor(props) {
super(props);
this.state = {
Extrashifts: [],
};
}
// componentDidMount() {
// this.fetchExtrashift();
// }
handleSubmit = (values) => {
console.log(values)
// axios
// .post("http://127.0.0.1:8000/api/create", {
// data: {
// title: this.target.elements.title.value,
// manager: this.data.item.manager,
// },
// })
// .then((res) => {
// if (res.status == 200) message.success("data successfully updated!");
// this.fetchExtrashift();
// })
// .catch((err) => {
// message.error("data profile failed to update ...");
// });
};
render() {
return (
<div>
<Form {...formItemLayout} name="update" onFinish={this.handleSubmit}>
<Form.Item label="Title :" name="title">
<Input placeholder="Put a title here" />
</Form.Item>
<Form.Item label="Manager :" name="manager">
<Input placeholder="Enter manager name" />
</Form.Item>
<Form.Item {...tailFormItemLayout}>
<Button
type="primary"
htmlType="submit"
>
create
</Button>
</Form.Item>
</Form>
</div>
);
}
}

TypeError: Cannot read property 'getters' of undefined on Vue Jest Test

This is my test file
import { shallowMount, createLocalVue } from '#vue/test-utils';
import Home from '#/views/Home.vue';
import Vuex from 'vuex';
import Vuetify from 'vuetify';
import movies from '#/store/modules/movies';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('Home.vue', () => {
let vuetify;
let store;
let state;
let actions;
beforeEach(() => {
state = {
movieList: [],
movieDetails: {},
};
actions = {
getMovieList: jest.fn(),
getMovieDetails: jest.fn(),
};
store = new Vuex.Store({
modules: {
movies: {
namespaced: true,
state,
actions,
},
},
});
vuetify = new Vuetify();
});
const wrapper = shallowMount(Home, {
store,
vuetify,
localVue,
});
it('should call submitForm() function when button is clicked', () => {
wrapper.find('button').trigger('click');
expect(wrapper.vm.submitForm).toHaveBeenCalled();
});
});
This is my view file
<script>
import Tooltip from '#/components/Tooltip.vue';
import { moviesComputed, moviesMethods } from '#/store/helpers/movies';
export default {
components: {
Tooltip,
},
methods: {
...moviesMethods,
submitForm() {
const validate = this.$refs.form.validate();
if (!validate) return;
this.currentPage = 1;
this.getMoviesList({ s: this.searchQuery });
},
async goToDetails(moveId) {
this.$router.push({ name: 'MovieDetails', params: { id: moveId } });
},
onScroll() {
const isOnBottom = document.documentElement.scrollTop + window.innerHeight
=== document.documentElement.offsetHeight;
if (isOnBottom) {
this.currentPage += 1;
this.nextMoviePage({ s: this.searchQuery, page: this.currentPage });
}
},
},
computed: {
...moviesComputed,
pagedMovieList() {
const listNumber = this.maxList * this.currentPage;
const list = this.movieList.filter((movie, index) => index < listNumber);
return list;
},
},
data() {
return {
searchQuery: '',
queryRules: [(v) => !!v || 'Antes de pesquisar, forneça um nome'],
mouseOverIndex: '',
maxList: 6,
currentPage: 1,
};
},
async mounted() {
document.addEventListener('scroll', this.onScroll);
},
beforeDestroy() {
document.removeEventListener('scroll', this.onScroll);
},
};
</script>
<template>
<div id="home">
<v-row class="justify-center align-center">
<v-col class="home-form" :class="{ 'to-top': movieList.length }" sm="12" md="6" xl="4">
<v-form ref="form" color="secondary" #submit="submitForm">
<v-text-field
label="Digite sua busca"
append-icon="mdi-magnify"
:rules="queryRules"
v-model="searchQuery"
required
/>
</v-form>
<v-btn color="secondary" class="mt-1" #click="submitForm">Enviar</v-btn>
</v-col>
</v-row>
<v-row class="mt-5">
<v-col
cols="12"
sm="6"
md="4"
v-for="(movie, index) in pagedMovieList"
:key="`${movie.Title}-${index}`"
style="position: relative"
>
<v-card elevation="10" #mouseover="mouseOverIndex = index" #mouseout="mouseOverIndex = ''">
<p class="mt-1 text-center" v-if="movie.Poster === 'N/A'">{{ movie.Title }}</p>
<v-img v-if="movie.Poster !== 'N/A'" :src="movie.Poster" />
<v-img v-else src="#/assets/not-found.png" />
<Tooltip #clicked="goToDetails" :active="index === mouseOverIndex" :movie="movie" />
</v-card>
</v-col>
</v-row>
</div>
</template>
This is my store module file
import { GetList, GetDetails } from '#/services/movies';
export const state = {
movieList: [],
movieDetails: {},
};
export const mutations = {
SET_LIST(state, newList) {
state.movieList = newList;
},
SET_MOVIE_DETAILS(state, newValue) {
state.movieDetails = newValue;
},
ADD_TO_LIST(state, list) {
state.movieList.push(...list);
},
};
export const actions = {
async getMoviesList({ commit }, query) {
const resp = await GetList(query);
if (resp.status === 200) commit('SET_LIST', resp.data.Search);
},
async getMovieDetails({ commit }, movieId) {
const resp = await GetDetails({ i: movieId });
if (!resp.status === 200) return;
commit('SET_MOVIE_DETAILS', resp.data);
},
async nextMoviePage({ commit }, query) {
const resp = await GetList(query);
if (resp.status === 200 && resp.data.Search) commit('ADD_TO_LIST', resp.data.Search);
},
};
const movies = {
namespaced: true,
mutations,
state,
actions,
};
export default movies;
This is my base.js module file
export const state = {
isLoading: false,
};
export const mutations = {
SET_LOADING(state, newValue) {
state.isLoading = newValue;
},
};
export const actions = {
setLoading({ commit }, value) {
commit('SET_LOADING', value);
},
};
const base = {
namespaced: true,
mutations,
state,
actions,
};
export default base;
And this is my store.js
import Vue from 'vue';
import Vuex from 'vuex';
// Modules
import Base from './modules/base';
import Movies from './modules/movies';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
base: Base,
movies: Movies,
},
strict: process.env.NODE_ENV !== 'production',
});
This is the error
TypeError: Cannot read property 'getters' of undefined
8 | Vue.use(Vuex);
9 |
> 10 | export default new Vuex.Store({
| ^
11 | modules: {
12 | base: Base,
13 | movies: Movies,
I have no idea why I'm getting an error on new Vuex.Store on tests. This application runs normally, without errors on Vuex. I cant even post what I already did to solve this because I'm completely lost

cordova.fileTransfer not updating page template Ionic2+Cordova

I have created an Ionic2 App using cordova FileTransferplugin, i am downloading remote server file.
Everything is working perfectly, but when I try to update template while fileTransfer.OnProgress event, the template is not updating the % downloaded.
Pleas see this video for my problem.
Ionic_youtube_link
My Code is, logic is in downloadFile function
import {Component, AfterViewInit, ViewChild} from '#angular/core';
import {NavController, NavParams, ViewController, Nav} from 'ionic-angular';
import {Page, Platform} from 'ionic-angular';
import {File, Device, Cordova, Transfer} from 'ionic-native';
import { SafeResourceUrl, DomSanitizationService } from '#angular/platform-browser';
#Component({
templateUrl: 'build/pages/video-download-modal/video-download-modal.html',
providers: [File, Transfer]
})
export class VideoDownloadModal {
selectedItem: any;
#ViewChild(Nav) nav: Nav;
videoPathUrl: string;
isPlatformReady: boolean;
platformName: string;
directoryName: string = "socialAppDir";
totalVideoSize:number;
totalDownloaded:number;
totalPercent:string = "0%";
constructor(public navCtrl: NavController, navParams: NavParams, private _viewController: ViewController, platform: Platform, private transfer:Transfer) {
// If we navigated to this page, we will have an item available as a nav param
if (platform.is('core')) {//if on dekstop
console.log('dektop');
} else {
this.videoPathUrl = navParams.get('videoPath');
console.log(this.videoPathUrl);
platform.ready().then((readySource) => {
this.isPlatformReady = true;
console.log('ready 1234');
const fs: string = cordova.file.externalRootDirectory;
console.log(cordova.file.dataDirectory);
this.platformName = Device.device.platform;
File.checkDir(cordova.file.externalDataDirectory, this.directoryName).then(() => {
console.log('directory exists');
this.downloadFile();
}, (error) => {
console.log('directory not exists');
this.createDirectory();
})
})
}
}
dismiss() {
let data = { 'foo': 'bar' };
this._viewController.dismiss(data);
}
createDirectory():void{
File.createDir(cordova.file.externalDataDirectory, this.directoryName, true).then(() => {
console.log("created externalDataDirectory");
this.downloadFile();
},(error) => {
console.log('some error happen')
})
}
downloadFile = () => {
console.log(this);
let fileName: string = this.videoPathUrl.split("/").pop();
let targetPath = cordova.file.externalDataDirectory + this.directoryName + "/" + fileName;
console.log(targetPath);
this.transfer.download(this.videoPathUrl, targetPath, true, {}).then(() => {
console.log('video downloaded')
}, (error) => {
console.log(error)
})
this.transfer.onProgress((progress) => {
console.log(this);
this.totalVideoSize = progress.total;
this.totalDownloaded = progress.loaded;
this.totalPercent = ((progress.loaded / progress.total) * 100).toString();
console.log(this.totalPercent);
})
}
ionViewDidEnter() {
console.log("enter login1");
}
}
And HTML is
<ion-content>
<div id="modalContainer" class="abd">
<ion-spinner></ion-spinner>
<br />
{{**totalPercent**}}
<br />
<button dnager block (click)="dismiss()">Exit</button>
</div>
</ion-content>
The totalPercent value either has 0 or 100.But not updating.
Please help.
This is because the totalPercent of this inside the handler was set to the global Window object instead of the object itself.
I have finally got it to work
import { NgZone } from '#angular/core';
fileTransfer.onProgress((progressEvent: ProgressEvent) => {
this.ngZone.run(() => {
if (progressEvent.lengthComputable) {
let lp = progressEvent.loaded / progressEvent.total * 100;
this.loadingPercent = Math.round(lp * 100) / 100;
}
});
})