react native navigatorIOS How to modify the state in the onLeftButtonPress? - react-native

How to modify the state in the onLeftButtonPress?Because I need to click to do animation, show or hide me is stored in the state
_getRoute(component) {
var com = new component();
return {
component: component,
title: com.getNavTitle(),
passProps: { myProp: 'foo' },
leftButtonIcon: com.getNavLeft().icon,
onLeftButtonPress: com.getNavLeft().onPress,
interactivePopGestureEnabled: true
};
}
getNavLeft() {
return {
icon: require('../Images/wo_de.png'),
onPress: () => {
console.log(this);
this.setState({leftShow: true});
Animated.timing( // Uses easing functions
this.state.leftWidthAnim, // The value to drive
{toValue: 0} // Configuration
).start();
}
};
}

Related

Nuxt asyncData result is undefined if using global mixin head() method

I'm would like to get titles for my pages dynamically in Nuxt.js in one place.
For that I've created a plugin, which creates global mixin which requests title from server for every page. I'm using asyncData for that and put the response into storage, because SSR is important here.
To show the title on the page I'm using Nuxt head() method and store getter, but it always returns undefined.
If I place this getter on every page it works well, but I would like to define it only once in the plugin.
Is that a Nuxt bug or I'm doing something wrong?
Here's the plugin I wrote:
import Vue from 'vue'
import { mapGetters } from "vuex";
Vue.mixin({
async asyncData({ context, route, store, error }) {
const meta = await store.dispatch('pageMeta/setMetaFromServer', { path: route.path })
return {
pageMetaTitle: meta
}
},
...mapGetters('pageMeta', ['getTitle']),
head() {
return {
title: this.getTitle, // undefined
// title: this.pageMetaTitle - still undefined
};
},
})
I would like to set title in plugin correctly, now it's undefined
Update:
Kinda solved it by using getter and head() in global layout:
computed: {
...mapGetters('pageMeta', ['getTitle']),
}
head() {
return {
title: this.getTitle,
};
},
But still is there an option to use it only in the plugin?
Update 2
Here's the code of setMetaFromServer action
import SeoPagesConnector from '../../connectors/seoPages/v1/seoPagesConnector';
const routesMeta = [
{
path: '/private/kredity',
dynamic: true,
data: {
title: 'TEST 1',
}
},
{
path: '/private/kreditnye-karty',
dynamic: false,
data: {
title: 'TEST'
}
}
];
const initialState = () => ({
title: 'Юником 24',
description: '',
h1: '',
h2: '',
h3: '',
h4: '',
h5: '',
h6: '',
content: '',
meta_robots_content: '',
og_description: '',
og_image: '',
og_title: '',
url: '',
url_canonical: '',
});
export default {
state: initialState,
namespaced: true,
getters: {
getTitle: state => state.title,
getDescription: state => state.description,
getH1: state => state.h1,
},
mutations: {
SET_META_FIELDS(state, { data }) {
if (data) {
Object.entries(data).forEach(([key, value]) => {
state[key] = value;
})
}
},
},
actions: {
async setMetaFromServer(info, { path }) {
const routeMeta = routesMeta.find(route => route.path === path);
let dynamicMeta;
if (routeMeta) {
if (!routeMeta.dynamic) {
info.commit('SET_META_FIELDS', routeMeta);
} else {
try {
dynamicMeta = await new SeoPagesConnector(this.$axios).getSeoPage({ path })
info.commit('SET_META_FIELDS', dynamicMeta);
return dynamicMeta && dynamicMeta.data;
} catch (e) {
info.commit('SET_META_FIELDS', routeMeta);
return routeMeta && routeMeta.data;
}
}
} else {
info.commit('SET_META_FIELDS', { data: initialState() });
return { data: initialState() };
}
return false;
},
}
}

Ask for permission in specific screen in android

For react native application navigation I use react-native-navigation v2 here I've created navigation with bottomTabs. Here is the navigation handler
import { Navigation } from "react-native-navigation";
import { width, height } from "../utils/screenResolution";
import { bottomTabIcon, topBarOpts } from "../components";
const sideBarWidth = width * 0.65;
export const goToAuth = () =>
Navigation.setRoot({
root: {
stack: {
id: "AuthNav",
children: [
{
component: {
name: "SignInScreen",
options: {
topBar: { visible: false, height: 0 }
}
}
}
]
}
}
});
export const goHome = async () => {
let icon1 = await bottomTabIcon("CollectionScreen", "Collection", "archive");
let icon2 = await bottomTabIcon("MainScreen", "Home", "home");
let icon3 = await bottomTabIcon("CaptureScreen", "Capture", "camera");
Navigation.setRoot({
root: {
sideMenu: {
right: {
component: {
name: "SideBar"
}
},
center: {
bottomTabs: {
id: "AppNav",
children: [icon1, icon2, icon3]
}
},
options: {
sideMenu: {
right: {
width: sideBarWidth
}
}
}
}
}
});
Navigation.mergeOptions("MainScreen", {
bottomTabs: {
currentTabIndex: 1
}
});
};
Icons tab creating with this bottomTabIcon function.
import Icon from "react-native-vector-icons/FontAwesome";
import { topBarOpts } from "./";
import { PRIMARY, BOTTOM_TAB_BACKGROUND, TAB_ICON } from "../../assets/color";
let bottomTabIcon = async (name, text, iconName) => {
let icon = {
stack: {
children: [
{
component: {
name: name,
id: name,
options: {
bottomTab: {
text: text,
fontSize: 12,
selectedIconColor: PRIMARY,
iconColor: TAB_ICON,
icon: await Icon.getImageSource(iconName, 20)
}
}
}
}
]
}
};
if (name === "CaptureScreen") {
icon.stack.children[0].component.options.bottomTabs = {
visible: false,
drawBehind: true,
animate: true
};
icon.stack.children[0].component.options.topBar = {
visible: false,
height: 0
};
} else {
icon.stack.children[0].component.options.bottomTabs = {
backgroundColor: BOTTOM_TAB_BACKGROUND
};
icon.stack.children[0].component.options.topBar = await topBarOpts("Example");
}
return icon;
};
export { bottomTabIcon };
Here is the problem, when user logging in application,its asking for permissions (camera,audio etc.) in MainScreen I want to do that in specific screen,after that I find out that all screens in bottomTabs mounted.So if I call something to do in componentDidMount in CaptureScreen it will work in MainScreen.How I can solve this part? I am pretty new in react-native so something you can find weird in this code.Thanks for help and for attention.
Have the permission calls only in did mount of the specific screens or in the child screen where it is needed not in the parent screen or in navigators.
In your case you are calling them by taking the route index in the react navigation. Add the permission code on the child screen or where the permissions are required and they will start working.

VueJS - vue-charts.js

I am trying to pass data I fetch from API to vue-chartjs as props, I am doing as in the documentation but it does not work.
Main component
<monthly-price-chart :chartdata="chartdata"/>
import MonthlyPriceChart from './charts/MonthlyPriceChart'
export default {
data(){
return {
chartdata: {
labels: [],
datasets: [
{
label: 'Total price',
data: []
}
]
},
options: {
responsive: true,
maintainAspectRatio: false
}
}
},
components: {
MonthlyPriceChart
},
created() {
axios.get('/api/stats/monthly')
.then(response => {
let rides = response.data
forEach(rides, (ride) => {
this.chartdata.labels.push(ride.month)
this.chartdata.datasets[0].data.push(ride.total_price)
})
})
.catch(error => {
console.log(error)
})
}
}
In response I have an array of obejcts, each of which looks like this:
{
month: "2018-10",
total_distance: 40,
total_price: 119.95
}
Then I want to send the data somehow to the chart so I push the months to chartdata.labels and total_price to chartdata.datasets[0].data.
chart component
import { Bar } from 'vue-chartjs'
export default {
extends: Bar,
props: {
chartdata: {
type: Array | Object,
required: false
}
},
mounted () {
console.log(this.chartdata)
this.renderChart(this.chartdata, this.options)
}
}
console.log(this.chartdata) outputs my chartsdata object from my main component and the data is there so the data is passed correctly to chart but nothing is rendered on the chart.
The documentation says this:
<script>
import LineChart from './LineChart.vue'
export default {
name: 'LineChartContainer',
components: { LineChart },
data: () => ({
loaded: false,
chartdata: null
}),
async mounted () {
this.loaded = false
try {
const { userlist } = await fetch('/api/userlist')
this.chartData = userlist
this.loaded = true
} catch (e) {
console.error(e)
}
}
}
</script>
I find this documentation a bit vague because it does not explain what I need to pass in chartdatato the chart as props. Can you help me?
Your issue is that API requests are async. So it happens that your chart will be rendered, before your API request finishes. A common pattern is to use a loading state and v-if.
There is an example in the docs: https://vue-chartjs.org/guide/#chart-with-api-data

Use a global alert across the react-native app

I'm a beginner for react-native and I need to alert to the user based on a status which will be retrieved from an API in every 15 seconds. For this I'm using react-native-background-timer in my main component to call the service. But when app is in some other screen (component) even though the service executes perfectly in the main component, it doesn't update it's props or status depending on the result it received (I guess this should be because I'm in a some other screen and props of main component will not be updated). Due to that alert will not be triggered if app is not in the main component
Can anyone please suggest me an approach for this?
class Home extends Component{
constructor(props){
super(props)
this._onPopUpShowed = this._onPopUpShowed.bind(this)
}
componentDidMount(){
//Initial call after the launch
this.props.fetchLiveOrderData()
//Start timer for polling
const intervalId = BackgroundTimer.setInterval(() => {
isBackgroudLoad=true
this.props.fetchLiveOrderData()
}, 1000*15);
}
render(){
const{payload,isFetching,isError,isSuccess} = this.props.liveOrderData
return(
//Render UI depending on the data fetched
);
}
}
//map state to props
const mapStateToProps = state => {
return {
liveOrderData: state.liveOrderData
}
}
//map dispatch to props
const mapDispatchToProps = dispatch => {
return {
fetchLiveOrderData : () => dispatch(fetchLiveOrderData())
}
}
export default connect(mapStateToProps, mapDispatchToProps) (Home)
liveOrderReducer.js
import {
FETCHING_LIVE_ORDER_DATA, FETCHING_LIVE_ORDER_DATA_SUCCESS, FETCHING_LIVE_ORDER_DATA_ERROR
} from '../constants'
const initialState = {
payload: [],
msg:[],
isFetching: true,
isError: false,
isSuccess: false
}
export default liveOrderReducer = (state = initialState, action) => {
switch(action.type){
case FETCHING_LIVE_ORDER_DATA :
return {
...state,
payload: [],
msg:[],
isFetching: true,
isError: false,
isSuccess: false
}
case FETCHING_LIVE_ORDER_DATA_SUCCESS :
return {
...state,
payload: action.data,
msg:[],
isFetching: false,
isError: false,
isSuccess:true
}
case FETCHING_LIVE_ORDER_DATA_ERROR :
return {
...state,
payload: [],
msg:action.msg,
isFetching: false,
isError: true,
isSuccess:false
}
default:
return state
}
}
index.js
import {
FETCHING_LIVE_ORDER_DATA, FETCHING_LIVE_ORDER_DATA_SUCCESS, FETCHING_LIVE_ORDER_DATA_ERROR
} from '../constants'
import api from '../lib/api'
export const getLiveOrderData = () => {
return {
type : FETCHING_LIVE_ORDER_DATA
}
}
export const getLiveOrderDataSuccess = data => {
return {
type : FETCHING_LIVE_ORDER_DATA_SUCCESS,
data
}
}
export const getLiveOrderDataFailure = () => {
return {
type : FETCHING_LIVE_ORDER_DATA_ERROR
}
}
export const fetchLiveOrderData = () => {
return(dispatch) => {
dispatch(getLiveOrderData())
api.getOrder().then(resp => {
dispatch(getLiveOrderDataSuccess(resp))
}).catch((err) => {
dispatch(getLiveOrderDataFailure(err))
})
}
}
Move the notification code to the container or the root component. This will ensure you will receive notifications even if the user moved away from the home screen.

Automatically closing Drawer when view width is decreasing

I'm trying to make a view like Firebase's console with React and material-ui.
How can I build a Drawer that will automatically close when view(browser) width is decreasing.
Quite easy, you can hook up the listener on resize event on your react class:
var RootPage = React.createClass({
render: function() {
return <Drawer refs={'drawer'} />;
},
// we trigger our drawer here
componentWillUpdate: function(nextProp, nextState) {
if(nextState.width < this.state.width) {
this.refs.drawer.open = false;
}
},
windowOnResize: function() {
var width = $(window).width();
this.setState({ width: width });
},
componentWillMount: function() {
this.windowOnResize();
},
componentDidMount: function() {
window.addEventListener("resize", this.windowOnResize);
},
componentWillUnmount: function() {
window.removeEventListener("resize", this.windowOnResize);
}
});