React-Native Redux this.props undefined - javascript

I am trying to use Redux to display data from firebase DB but for some reason this.props is undefined
I used redux to display another data in another pages from my DB with no problems.But here I stuck and can't find my mistake
Here is my code.I hope someone can give me advice what is wrong here
in my invoice.js I have :
const mapStateToProps = (state) => {
return {
startFireData: state.startFireData,
};
}
const mapDispatchToProps = (dispatch) => {
return {
watchInvoiceStartFire: () => { dispatch(watchInvoiceStartFire()) },
};
}
constructor(props) {
super(props);
this.props.watchInvoiceStartFire();
}
and in Render:
return (
<View style={styles.container}>
<LinearGradient
colors={['#3399ff', '#66b3ff', '#cccccc']}
style={styles.pageStyle}>
<Text style={styles.buttonText} >{this.props.startFireData.נפיץ}</Text>
<Text style={styles.buttonText} >{this.props.startFireData.עשן_חדש}</Text>
<Text style={styles.buttonText} >{this.props.startFireData.עשן_ישן}</Text>
<Text style={styles.buttonText} >דוחות</Text>
<Text style={styles.buttonText} >דוחות</Text>
</LinearGradient>
</View>
in my redux file:
const watchInvoiceStartFire = () =>{
return function(dispatch) {
firebase.database().ref("Invoices/startfire/ammo").on("value", function(snapshot) {
var startFireData = snapshot.val();
dispatch(setStartFireData(startFireData));
}, function(error) { });
};
}
const setStartFireData = (startFireData) =>{
return {
type: "setStartFireData",
value: startFireData
}
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case "setStorageData":
return { ...state, storageData: action.value };
case "setOperationData":
return {...state, operationData: action.value};
case "setStartFireData":
return {...state, startFireData: action.value};
default:
return state;
}
};
My mistake,I forgot to add to initial state
const initialState = {
personData: { },
storageData:{ },
operationData:{ },
startFireData:{ },
};
Sorry for bothering u here

Related

react native : infinite loop with useEffect

When I run the app then it goes into an infinite loop
This is because pointsData is inside the useEffect.
How can this situation be fix ?
function useGetPoints() {
const [pointsData, setPointsData] = useState<PointTbleType[]>([]);
React.useEffect(() => {
loadDataFromPointTables()
}, [])
const loadDataFromPointTables = () => {
(async () => {
try {
const points = await PointTable.getPointList()
setPointsData(points);
// if (!points.length) {
// Toast.show({ type: 'info', text1: 'There is no data in the table point' })
// }
} catch (error) {
console.warn('Error from loadDataFromPointTables(): ', error);
}
})();
}
return {
pointsData
}
}
export const PointModal = (props: any) => {
const { pointsData } = useGetPoints();
const [tableHead] = useState(['Area', 'Site', 'Collection Point', 'Location']);
const [tableData, setTableData] = useState<any[]>([]);
const arrangeData = () => {
let rows: any[] = [];
pointsData.forEach(e => {
let row = [e.Area, e.Site, e.GatheringPoint, e.Location];
rows.push(row);
});
setTableData(rows);
}
useEffect(() => {
arrangeData();
}, [pointsData]);
return (
<Modal
animationType={'slide'}
transparent={false}
visible={props.pointModalVisible}
onRequestClose={() => {
console.log('Modal has been closed.');
}}>
<View style={styles.modal}>
{pointsData.length ?
<ScrollView style={styles.item}>
<View style={styles.tableView}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
<Row data={tableHead} style={styles.head} textStyle={styles.text} />
<Rows data={tableData} textStyle={styles.text} />
</Table>
</View>
</ScrollView>
:
<ActivityIndicator size="large" color='white' />}
</View>
<Button
title="CLOSE"
onPress={props.onClose}
/>
</Modal>
);
};
It is very obvious that it will run into an infinite loop. You're giving pointsData as dependency of useEffect and loadDataFromPointTables is dispatching value to pointsData. Remove pointsData as dependency and every will work as expected.
This is because you don't check if pointsData is not empty.
First of all I would set pointsData to null or undefined in the beginning:
const [pointsData, setPointsData] = useState<PointTbleType[]>(undefined);
and later on you have to check if it is not null or undefined and then call function to fetch data:
React.useEffect(() => {
if(!pointsData){
loadDataFromPointTables();
}
}, [pointsData])
Second option is to just remove pointsData from dependancy array in useEffect so it will run only once.
This is because you haven't set any condition while updating pointsData. Give a try with below code it should work
function useGetPoints() {
const [pointsData, setPointsData] = useState<PointTbleType[]>([]);
React.useEffect(() => {
loadDataFromPointTables()
}, [pointsData])
const loadDataFromPointTables = () => {
(async () => {
try {
const points = await PointTable.getPointList()
if(points != pointsData){
setPointsData(points);
}
} catch (error) {
console.warn('Error from loadDataFromPointTables(): ', error);
}
})();
}
return {
pointsData
}
}

Increment and decrement counter with input using redux

I want to increase and decrease the counter.counter1 and counter.counter2.innerCount by input value.
Here is the error I found now
I am weak at destructing object etc. and now learning for it.
Could provide me any advice or code? Especially for increment and decrement for innerCount. Much appreciate.
actionCreators.js
import * as actionTypes from "../actionTypes";
export const incrementCounter1 = () => {
return {
type: ActionTypes.INCREMENT_COUNTER_1,
};
};
export const decrementCounter1 = () => {
return {
type: ActionTypes.DECREMENT_COUNTER_1,
};
};
export const incrementByAmount = (amount) => {
return {
type: ActionTypes.INCREMENT_BY_AMOUNT,
amount:amount,
};
};
reducer.js
import * as actionTypes from "../actionTypes";
const INITIAL_STATE = {
counter: {
counter1: 0,
counter2: {
innerCount: 0,
},
},
};
export const Auth = (state = INITIAL_STATE, action) => {
const { type, payload } = action;
let a;
switch (type) {
case ActionTypes.INCREMENT_COUNTER_1:
a = {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 +=1,
},
};
return a;
case ActionTypes.DECREMENT_COUNTER_1:
a = {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 -=1,
},
};
return a;
case ActionTypes.INCREMENT_BY_AMOUNT:
a = {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 +=payload,
},
};
return a;
default:
return state;
}
};
export default Auth;
mainPage.js
import React, { useState } from "react";
import { View, Text, StyleSheet, Button, TextInput } from "react-native";
import {
incrementCounter1,
decrementCounter1,
incrementByAmount,
} from "./states/redux/ActionCreators/auth";
import { connect } from "react-redux";
const Counter = ({
counterRedux,
incrementCounter1,
decrementCounter1,
incrementByAmount,
}) => {
const [amount, setAmount] = useState('');
return (
<View>
<Text style={styles.text}>Input text for changing</Text>
<Button title="INCREMENT" onPress={() => incrementCounter1()} />
<Button title="DECREMENT" onPress={() => decrementCounter1()} />
<View>
<Text style={styles.Atext}>Enter amount to increase:</Text>
<TextInput style={styles.input} value={amount} onChangeText={(a) => setAmount(a)} />
<Text style={styles.Atext}>Amount: {amount}</Text>
<Button title='Add Amount' onPress={(amount)=>incrementByAmount(amount)}></Button>
</View>
<View>
<Text style={styles.Atext}>First Counter: {counterRedux.counter1}</Text>
</View>
</View>
);
};
const mapStateToProps = (state) => {
return {
counterRedux: state.counter,
};
};
const mapDispatchToProps = (dispatch) => {
return {
incrementCounter1: () => dispatch(incrementCounter1()),
decrementCounter1: () => dispatch(decrementCounter1()),
incrementByAmount: (amount) => dispatch(incrementByAmount(amount)),
};
};
const styles = StyleSheet.create({
text: {
fontSize: 25,
},
Atext: {
fontSize: 20,
},
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
input: {
borderWidth: 1,
borderColor: "#777",
padding: 8,
margin: 10,
width: 200,
},
button: {
backgroundColor: "#fff",
fontSize: 15,
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
actionTypes.js
export const INCREMENT_BY_AMOUNT = 'INCREMENT_BY_AMOUNT';
export const INCREMENT_COUNTER_1 = 'INCREMENT_COUNTER_1';
export const DECREMENT_COUNTER_1 = 'DECREMENT_COUNTER_1';
Your first issue is here: <Button title='Add Amount' onPress={(amount)=>incrementByAmount(amount)}></Button>.
What you are doing is passing to incrementByAmount the argument passed by onPress which is not at all the amount you expect, but a PressEvent object.
In order to receive the amount you expect, you need to do this: <Button title='Add Amount' onPress={() => incrementByAmount(amount)}></Button> so you get the amount from useState.
Also you definitely don't need to have three actions for your counter, a simpler way to do it would be to have an updateAmount function to which you pass as payload a type that would be "increment" or "decrement", and an amount.
An even simpler way would be to only have an amount and pass either a negative or a positive value to it.
For your increment and decrement buttons, you would simply need to pass 1 or -1 as amount.
Your second issue is that you are mutating your state in your reducer with the += and -= operators.
Here is your fixed reducer (I will let you implement the changes I suggested earlier though):
import * as actionTypes from "../actionTypes";
const INITIAL_STATE = {
counter: {
counter1: 0,
counter2: {
innerCount: 0,
},
},
};
export const Auth = (state = INITIAL_STATE, action) => {
const { type, payload } = action;
switch (type) {
case ActionTypes.INCREMENT_COUNTER_1:
return {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 + 1,
},
};
case ActionTypes.DECREMENT_COUNTER_1:
return {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 - 1,
},
};
case ActionTypes.INCREMENT_BY_AMOUNT:
return {
...state,
counter: {
...state.counter,
counter1: state.counter.counter1 + payload,
},
};
default:
return state;
}
};
export default Auth;
I removed the a variable that wasn't needed and changed the += operator to + and the -= operator to - so your state isn't mutated.
Your third issue is that you are destructuring a variable payload while it is called amount in your action creator.
Also don't forget that you are getting a string from <TextInput> and not a number.
Finally you import your action types as actionTypes but use them as ActionTypes.

React Native, component is not closing

I created a shopping app with react native and redux, I'm facing a problem that when a user click buy it should view a component in bottom that will show total amount and view cart button and when user remove item from cart and cart is empty, it should close/state set to false, but it's not going away. Can anyone tell me what's wrong, below is my code
reducer.js
if (action.type === SHOW_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
if (addedItem == 0) {
return {
...state,
show: console.log(state.showCart),
};
} else {
return {
...state,
show: console.log(action.showCart),
};
}
}
const initialstate = {
showChart: false,
}
that's my reducer where I'm handling that function
action.js
export const showCart = (id) => {
return {
type: SHOW_CART,
showCart: true,
id,
};
};
that's my action where I describe it's action
ViewCart.js
<View>
{this.props.show ? (
<View style={styles.total}>
<Text style={styles.totaltext}>Total:</Text>
<Text style={styles.priceTotal}>{this.props.total}</Text>
<View style={styles.onPress}>
<Text
style={styles.pressText}
onPress={() => RootNavigation.navigate("Cart")}
>
View Cart
</Text>
</View>
</View>
) : null}
</View>
const mapStateToProps = (state) => {
return {
total: state.clothes.total,
show: state.clothes.show,
};
};
that's the function where I'm using that reducer
By my opinion, the problem is located in your reducer.js file
if (action.type === SHOW_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
if (addedItem.quantity > 0) {
return {
...state,
showCart: action.showCart, // here was the problem
};
}
}
const initialstate = {
showChart: false,
}
Please try it and tell me what goes on.
And let me suggest to add another test to your if statement :
if (addedItem && addedItem.quantity > 0)
To avoid probable trouble by an unexpected manipulation

Redux store isn't getting updated

I have built this app using create-react-native-app, the action is dispatched but the state isn't being updated and I'm not sure why.
I see the action being logged (using middleware logger) but the store isn't getting updated, I am working on Add_Deck only for now
Here is my reducer:
// import
import { ADD_CARD, ADD_DECK } from './actions'
// reducer
export default function decks(state ={}, action){
switch(action.type){
case ADD_DECK:
return {
...state,
[action.newDeck.id]: action.newDeck
}
case ADD_CARD:
return {
...state,
[action.deckID]: {
...state[action.deckID],
cards: state[action.deckID].cards.concat([action.newCard])
}
}
default: return state
}
}
Actions file:
// action types
const ADD_DECK = "ADD_DECK";
const ADD_CARD = "ADD_CARD";
// generate ID function
function generateID() {
return (
"_" +
Math.random()
.toString(36)
.substr(2, 9)
);
}
// action creators
function addDeck(newDeck) {
return {
type: ADD_DECK,
newDeck
};
}
// export
export function handleAddDeck(title) {
return dispatch => {
const deckID = generateID();
// const newDeck = { id: deckID, title, cards: [] };
dispatch(addDeck({ id: deckID, title, cards: [] }));
};
}
function addCard(deckID, newCard) {
// { question, answer }, deckID
return {
type: ADD_CARD,
deckID,
newCard
};
}
// export
export function handleAddCard(deckID, content) {
// { question, answer }, deckID
return dispatch => {
const newCard = { [generateID()]: content };
dispatch(addCard(deckID, newCard));
};
}
And react-native component:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import {red, white} from '../utils/colors'
import { connect } from 'react-redux'
import { handleAddDeck } from '../redux/actions'
class AddDeck extends Component {
state = {
text:""
}
handleSubmit = () => {
this.props.dispatch(handleAddDeck(this.state.text))
this.setState(()=>{
return { text: ""}
})
}
render() {
return (
<View style={styles.adddeck}>
<Text> This is add deck</Text>
<TextInput
label="Title"
style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
onChangeText={text => this.setState({ text })}
placeholder="Deck Title"
value={this.state.text}
/>
<TouchableOpacity style={styles.submitButton} onPress={this.handleSubmit}>
<Text style={styles.submitButtonText}>Create Deck</Text>
</TouchableOpacity>
</View>
);
}
}
function mapStateToProps(decks){
console.log("state . decks", decks)
return {
decks
}
}
export default connect(mapStateToProps)(AddDeck);
const styles = StyleSheet.create({
adddeck: {
marginTop: 50,
flex: 1
},
submitButton: {
backgroundColor: red,
padding: 10,
margin: 15,
height: 40,
},
submitButtonText: {
color: white
}
});
I guess you forgot to export your types from the actions file thus the switch(action.type) does not trigger the needed case statement.
Maybe try to add as the following:
export const ADD_DECK = "ADD_DECK";
export const ADD_CARD = "ADD_CARD";
Or further debugging just to see if the values are the ones what you are looking for:
export default function decks(state = {}, action) {
console.log({type:action.type, ADD_DECK}); // see what values the app has
// further code ...
}
I hope that helps! If not, let me know so we can troubleshoot further.

How do I pass the answer from application state as a prop and not the internal state of the card

I have a component that is giving me the following issues:
TEST STEPS:
Login to Mobile.
On the Activity Feed, answer the first Get Involved question.
Scroll to the last Get Involved question and answer it.
Scroll back to the first Get Involved question that was answered.
EXPECTED RESULTS:
The answer for the first Get Involved question should still be selected.
ACTUAL RESULTS:
It is not selected.
So it seems the issue is the callback that updates some state on the parent, but the parent is not passing the yes/no prop to this component and it's unmounting to spare me rendering.
On the backend, in the database, the answers are being recorded, but it's not persisting in the UI. I noticed that the helper functions below, specifically the this.props.onPress() return undefined.
class GetInvolvedFeedCard extends PureComponent {
static propTypes = {
onPress: PropTypes.func.isRequired,
style: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
title: PropTypes.string.isRequired
};
constructor(props) {
super(props);
const helper = `${
this.props.title.endsWith("?") ? "" : "."
} Your NFIB preferences will be updated.`;
this.state = {
noSelected: false,
yesSelected: false,
helper
};
}
_accept = () => {
this.setState({ yesSelected: true, noSelected: false }, () => {
this.props.onPress(true);
});
};
_decline = () => {
this.setState({ noSelected: true, yesSelected: false }, () => {
this.props.onPress(false);
});
};
render() {
return (
<Card style={this.props.style}>
<View style={feedContentStyles.header}>
<View style={feedContentStyles.contentType}>
<Text style={feedContentStyles.title}>{"GET INVOLVED"}</Text>
</View>
</View>
<Divider />
<View style={feedContentStyles.content}>
<View style={styles.content}>
<Text style={styles.blackTitle}>
{this.props.title}
<Text style={styles.italicText}>{this.state.helper}</Text>
</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity onPress={this._decline}>
<Text
style={[
styles.btnText,
styles.noBtn,
this.state.noSelected ? styles.selected : null
]}
>
{"NO"}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this._accept}>
<Text
style={[
styles.btnText,
this.state.yesSelected ? styles.selected : null
]}
>
{"YES"}
</Text>
</TouchableOpacity>
</View>
</View>
</Card>
);
}
}
So it appears that the state is being managed by the parent component as opposed to Redux.
What is unclear is, whether or not it is unmounting the component that defines onPress. It sounds like it is.
Just scrolling, so there is an activity feed composed of cards some of them render boolean type questions
do you want to get involved? no yes
When a user selects either response, then scrolls down a certain amount and then scrolls back up to that same question, it's like the user never answered it. I noticed when the user selects NO, the this.props.handleUpdateGetInvolved({ involved: items }) from _handleGetInvolved function is not fired only when the user selects YES. Referring to this:
_handleGetInvolved = (response, entity) => {
if (response !== entity.IsSelected) {
const isTopic = entity.Category !== "GetInvolved";
const items = [
{
...entity,
IsSelected: response
}
];
if (isTopic) {
this.props.handleUpdateTopics({ topics: items });
} else {
this.props.handleUpdateGetInvolved({ involved: items });
}
}
};
the helper functions themselves for each answer always returns undefined inside the GetInvolvedFeedCard component:
_accept = () => {
this.setState({ yesSelected: true, noSelected: false }, () => {
this.props.onPress(true);
console.log(
"this is the accept helper function: ",
this.props.onPress(true)
);
});
};
_decline = () => {
this.setState({ noSelected: true, yesSelected: false }, () => {
this.props.onPress(false);
console.log(
"this is the decline helper function: ",
this.props.onPress(false)
);
});
};
render() {
return (
<Card style={this.props.style}>
<View style={feedContentStyles.header}>
<View style={feedContentStyles.contentType}>
<Text style={feedContentStyles.title}>{"GET INVOLVED"}</Text>
</View>
</View>
<Divider />
<View style={feedContentStyles.content}>
<View style={styles.content}>
<Text style={styles.blackTitle}>
{this.props.title}
<Text style={styles.italicText}>{this.state.helper}</Text>
</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity onPress={this._decline}>
<Text
style={[
styles.btnText,
styles.noBtn,
this.state.noSelected ? styles.selected : null
]}
>
{"NO"}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this._accept}>
<Text
style={[
styles.btnText,
this.state.yesSelected ? styles.selected : null
]}
>
{"YES"}
</Text>
</TouchableOpacity>
</View>
If I am not mistaken all this is being rendered overall by the ActivityFeed component:
const { height } = Dimensions.get("window");
export class ActivityFeed extends PureComponent {
static propTypes = {
displayAlert: PropTypes.bool,
feed: PropTypes.array,
fetchFeed: PropTypes.func,
getCampaignDetails: PropTypes.func,
handleContentSwipe: PropTypes.func,
handleUpdateGetInvoved: PropTypes.func,
handleUpdateTopics: PropTypes.func,
hideUndoAlert: PropTypes.func,
lastSwippedElement: PropTypes.object,
loading: PropTypes.bool,
navigation: PropTypes.object,
setSelectedAlert: PropTypes.func,
setSelectedArticle: PropTypes.func,
setSelectedEvent: PropTypes.func,
setSelectedSurvey: PropTypes.func.isRequired,
undoSwipeAction: PropTypes.func,
userEmailIsValidForVoterVoice: PropTypes.bool
};
constructor(props) {
super(props);
this.prompted = false;
this.state = {
refreshing: false,
appState: AppState.currentState
};
}
async componentDidMount() {
AppState.addEventListener("change", this._handleAppStateChange);
if (!this.props.loading) {
const doRefresh = await cache.shouldRefresh("feed");
if (this.props.feed.length === 0 || doRefresh) {
this.props.fetchFeed();
}
cache.incrementAppViews();
}
}
componentWillUnmount() {
AppState.removeEventListener("change", this._handleAppStateChange);
}
_handleAppStateChange = async appState => {
if (
this.state.appState.match(/inactive|background/) &&
appState === "active"
) {
cache.incrementAppViews();
const doRefresh = await cache.shouldRefresh("feed");
if (doRefresh) {
this.props.fetchFeed();
}
}
this.setState({ appState });
};
_keyExtractor = ({ Entity }) =>
(Entity.Key || Entity.Id || Entity.CampaignId || Entity.Code).toString();
_gotoEvent = event => {
cache.setRouteStarter("MainDrawer");
this.props.setSelectedEvent(event);
const title = `${event.LegislatureType} Event`;
this.props.navigation.navigate("EventDetails", { title });
};
_gotoSurveyBallot = survey => {
cache.setRouteStarter("MainDrawer");
this.props.setSelectedSurvey(survey);
this.props.navigation.navigate("SurveyDetails");
};
_gotoArticle = article => {
cache.setRouteStarter("MainDrawer");
this.props.setSelectedArticle(article);
this.props.navigation.navigate("ArticleDetails");
};
_onAlertActionButtonPress = async item => {
cache.setRouteStarter("MainDrawer");
await this.props.setSelectedAlert(item.Entity);
this.props.getCampaignDetails();
if (this.props.userEmailIsValidForVoterVoice) {
this.props.navigation.navigate("Questionnaire");
} else {
this.props.navigation.navigate("UnconfirmedEmail");
}
};
_onSwipedOut = (swippedItem, index) => {
this.props.handleContentSwipe(this.props, { swippedItem, index });
};
_handleGetInvolved = (response, entity) => {
if (response !== entity.IsSelected) {
const isTopic = entity.Category !== "GetInvolved";
const items = [
{
...entity,
IsSelected: response
}
];
if (isTopic) {
this.props.handleUpdateTopics({ topics: items });
} else {
this.props.handleUpdateGetInvoved({ involved: items });
}
}
};
renderItem = ({ item, index }) => {
const { Type, Entity } = item;
if (Type === "EVENT") {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<EventFeedCard
style={styles.push}
mainActionButtonPress={() => this._gotoEvent(Entity)}
event={Entity}
/>
</SwippableCard>
);
}
if (["SURVEY_SURVEY", "SURVEY_BALLOT"].includes(Type)) {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<SurveyBallotFeedCard
style={styles.push}
survey={Entity}
handleViewDetails={() => this._gotoSurveyBallot(Entity)}
/>
</SwippableCard>
);
}
if (Type === "SURVEY_MICRO") {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<MicroSurvey style={styles.push} selectedSurvey={Entity} />
</SwippableCard>
);
}
if (Type === "ALERT") {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<ActionAlertFeedCard
datePosted={Entity.StartDateUtc}
style={styles.push}
title={Entity.Headline}
content={Entity.Alert}
mainActionButtonPress={() => this._onAlertActionButtonPress(item)}
secondaryActionButtonPress={() => {
this.props.setSelectedAlert(Entity);
// eslint-disable-next-line
this.props.navigation.navigate("ActionAlertDetails", {
content: Entity.Alert,
id: Entity.CampaignId,
title: Entity.Headline
});
}}
/>
</SwippableCard>
);
}
if (Type === "ARTICLE") {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<ArticleFeedCard
content={Entity}
style={styles.push}
mainActionButtonPress={() => this._gotoArticle(Entity)}
/>
</SwippableCard>
);
}
//prettier-ignore
if (Type === 'NOTIFICATION' && Entity.Code === 'INDIVIDUAL_ADDRESS_HOME_MISSING') {
return (
<MissingAddressCard
style={styles.push}
navigate={() => this.props.navigation.navigate('HomeAddress')}
/>
);
}
if (["PREFERENCE_TOPIC", "PREFERENCE_INVOLVEMENT"].includes(Type)) {
return (
<SwippableCard onSwipedOut={() => this._onSwipedOut(item, index)}>
<GetInvolvedFeedCard
style={styles.push}
title={Entity.DisplayText}
onPress={response => this._handleGetInvolved(response, Entity)}
/>
</SwippableCard>
);
}
return null;
};
_onRefresh = async () => {
try {
this.setState({ refreshing: true });
this.props
.fetchFeed()
.then(() => {
this.setState({ refreshing: false });
})
.catch(() => {
this.setState({ refreshing: false });
});
} catch (e) {
this.setState({ refreshing: false });
}
};
_trackScroll = async event => {
try {
if (this.prompted) {
return;
}
const y = event.nativeEvent.contentOffset.y;
const scrollHeight = height * 0.8;
const page = Math.round(Math.floor(y) / scrollHeight);
const alert = await cache.shouldPromtpPushNotificationPermissions();
const iOS = Platform.OS === "ios";
if (alert && iOS && page > 1) {
this.prompted = true;
this._openPromptAlert();
}
} catch (e) {
return false;
}
};
_openPromptAlert = () => {
Alert.alert(
"Push Notifications Access",
"Stay engaged with NFIB on the issues and activities you care about by allowing us to notify you using push notifications",
[
{
text: "Deny",
onPress: () => {
cache.pushNotificationsPrompted();
},
style: "cancel"
},
{
text: "Allow",
onPress: () => {
OneSignal.registerForPushNotifications();
cache.pushNotificationsPrompted();
}
}
],
{ cancelable: false }
);
};
_getAlertTitle = () => {
const { lastSwippedElement } = this.props;
const { Type } = lastSwippedElement.swippedItem;
if (Type.startsWith("PREFERENCE")) {
return "Preference Dismissed";
}
switch (Type) {
case "EVENT":
return "Event Dismissed";
case "SURVEY_BALLOT":
return "Ballot Dismissed";
case "SURVEY_SURVEY":
return "Survey Dismissed";
case "SURVEY_MICRO":
return "Micro Survey Dismissed";
case "ARTICLE":
return "Article Dismissed";
case "ALERT":
return "Action Alert Dismissed";
default:
return "Dismissed";
}
};
render() {
if (this.props.loading && !this.state.refreshing) {
return <Loading />;
}
const contentStyles =
this.props.feed.length > 0 ? styles.content : emptyStateStyles.container;
return (
<View style={styles.container}>
<FlatList
contentContainerStyle={contentStyles}
showsVerticalScrollIndicator={false}
data={this.props.feed}
renderItem={this.renderItem}
keyExtractor={this._keyExtractor}
removeClippedSubviews={false}
onRefresh={this._onRefresh}
refreshing={this.state.refreshing}
ListEmptyComponent={() => (
<EmptyState navigation={this.props.navigation} />
)}
scrollEventThrottle={100}
onScroll={this._trackScroll}
/>
{this.props.displayAlert && (
<BottomAlert
title={this._getAlertTitle()}
onPress={this.props.undoSwipeAction}
hideAlert={this.props.hideUndoAlert}
/>
)}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
content: {
paddingHorizontal: scale(8),
paddingTop: scale(16),
paddingBottom: scale(20)
},
push: {
marginBottom: 16
}
});
const mapState2Props = ({
activityFeed,
auth: { userEmailIsValidForVoterVoice },
navigation
}) => {
return {
...activityFeed,
userEmailIsValidForVoterVoice,
loading: activityFeed.loading || navigation.deepLinkLoading
};
};
export default connect(mapState2Props, {
fetchFeed,
getCampaignDetails,
handleUpdateGetInvoved,
handleUpdateTopics,
setSelectedAlert,
setSelectedArticle,
setSelectedEvent,
setSelectedSurvey,
handleContentSwipe,
undoSwipeAction,
hideUndoAlert
})(ActivityFeed);
This is what the Get Involved card looks like:
So when the user clicks NO or YES, then scrolls that card away from view, the expectation is when they scroll that card back into view NO or YES, whichever one selected, should still be there.
Also, the answer selected only disappears when the user scrolls all the way to the bottom of the activity feed and then back up, but if the user only scrolls halfway through the activity feed cards and returns to this Get Involved card, the answer selected does not go away.
I believe the below SO article answer is exactly what is happening to me:
React Native - FlatList - Internal State.
So it seems the answer here would be to pass the answer from the application state as a prop and render based on that prop, and not the internal state of the card but I am not entirely sure what that looks like or how to put it together.
constructor(props) {
super(props);
// const helper = `${
// this.props.title.endsWith("?") ? "" : "."
// } Your NFIB preferences will be updated.`;
this.state = {
noSelected: false,
yesSelected: false,
helper
};
}
_accept = () => {
this.setState({ yesSelected: true, noSelected: false }, () => {
this.props.onPress(true);
});
};
_decline = () => {
this.setState({ noSelected: true, yesSelected: false }, () => {
this.props.onPress(false);
});
};
with:
this.state = {
// noSelected: false,
// yesSelected: false,
// helper
cardSelectedStatus: []
};
with the idea of then implementing cardSelectedStatus in my mapStateToProps
function mapStateToProps(state) {
return {cardSelectedStatus: state.};
}
but then I realized I am not sure what I am passing in as there are no action creators involved in this component, therefore no reducers
so can I use mapStateToProps if there is no action creator/reducer involved in this component?
utilizing mapStateToProps is the only way I know or its the way with the most experience I have in passing the user's input from the application state as a prop and render based on that prop, and not the internal state.
I can guess the problem. The problem is you are using something like FlatList. It will recreate the card every time you scroll it over screen, then scroll back.
So there are 2 ways to fix it:
Using ScrollView. It won't recreate cards
Move card states out of the Card component. Move them to List state. So in List state you will have something like:
this.state = {
cardSelectedStatus: [], // array [true, false, true, ...]. Mean card 0: selected, card 1: no selected,...
...
};
Then you can pass state to each card
So after several weeks of hammering away at this and posting the above question, here is what I finally honed in on:
By default the data for the preference is set to isSelected: false in the Redux state.
If I hit Yes, the Redux state is updated. This changes the isSelected to true.
If I hit No after hitting Yes, the Redux state is NOT updated, it stays isSelected: true.
So based on this, because isSelected does not have a neutral value, that is, starts out as false, which would equate to No, I cannot rely on Redux state for rendering the selection, which could have solved this.
Instead, in the interest of time, the only solution I could think of with much input from others includint tuledev, was to set <FlatList windowSize={500} />.
This is not an elegant solution but it will get FlatList to behave more like ScrollView in that preserve all the components so my component state will not get wiped out when a user scrolls to far away from it. This works without actually replacing it to ScrollView since there are properties and methods with FlatList that would not work by just dropping it into ScrollView same as it is in FlatList, for example, there is no renderItem property in ScrollView.

Categories

Resources