Variable Keeps Changing its Own Value to be Every View Prop - react-native

I am working in React Native and have encountered an error I have never seen before. I have a couple of nested mapping functions to help render a list of user accounts. The point of this is to list every user so that you can add or remove them from a groupchat. This means I need to track each users' ids and compare it to the ids of users already in the groupchat (so you can remove ones who are already in and add ones who are not, and NOT vice versa). The issue I am facing is that whatever variable I put into the function that dictates whether and add button or remove button is shown is that the id entered into the function keeps changing its value. I have console.log statements before every function call and it logs the user's uuid properly every time, but once it goes into the function, the value somehow changes from the uuid to a JSON object of what appears to be all possible View props. My code is below...
import React, {useState} from "react";
import { View, Text, ScrollView, TouchableOpacity, Touchable } from 'react-native'
import { useQuery } from "#apollo/client";
import { DRIVERSGETDRIVERSFROMDSP } from "../../../GraphQL/operations";
import Banner from "../../../Global/Banner";
import Loading from "../../../Global/Loading";
import { ContactStyles } from "../../../Styles/CommunicationStyles";
import nameObj from "../../../Hooks/handleNameCaseChange";
import dateObj from "../../../Hooks/handleDateTime";
import { useRecoilState } from 'recoil'
import { threadState, userState } from "../../../Recoil/atoms";
const Contacts = ({creating}) => {
// Gets all Drivers from DSP
const {loading: loading, error: error, data: queryData} = useQuery(DRIVERSGETDRIVERSFROMDSP)
// -------------------- Recoil and UseState ----------------------
// Recoil
// Gets User
const [user, setUser] = useRecoilState(userState);
// Gets Thread
const [thread, setThread] = useRecoilState(threadState)
// UseState
// keeps track of driver contacts added to groupchat
const[newGuests, setNewGuests] = useState([])
// -------------------- Recoil and UseState ----------------------
// --------------- Rendering and Generating Functions ------------
const renderRoster = (list) => {
let i = 0
return( list.map( (driver) => {
const namer = nameObj(driver.firstname, driver.lastname)
i++
return(
<View style={ContactStyles.card} key={i}>
<View style={ContactStyles.image}><Text>Image</Text></View>
<View style={ContactStyles.nameView}><Text style={ContactStyles.title}>{namer.first} {namer.last} </Text></View>
{determineAddOrRemove(driver.id)}
<View style={ContactStyles.divider} />
</View>
)
}))
}
const determineAddOrRemove = (selectedId) => {
if (creating){
if (newGuests.length > 0){
newGuests.forEach( (driver) => {
if (driver.id === selectedId){
console.log(selectedId)
return(
<TouchableOpacity style={ContactStyles.removeButton} onPress={(s) => handleRemoveClick(selectedId)}>
<View><Text style={ContactStyles.removeText}>Remove</Text></View>
</TouchableOpacity>
)
}
})
console.log(selectedId)
return(
<TouchableOpacity style={ContactStyles.addButton} onPress={(selectedId) => handleAddClick(selectedId)}>
<View><Text style={ContactStyles.addText}>Add</Text></View>
</TouchableOpacity>
)
}
console.log(selectedId)
return(
<TouchableOpacity style={ContactStyles.addButton} onPress={(selectedId) => handleAddClick(selectedId)}>
<View><Text style={ContactStyles.addText}>Add</Text></View>
</TouchableOpacity>
)
}
thread = [...thread, newGuests]
thread.forEach( (driver) => {
if (driver.id === selectedId){
console.log(selectedId)
return(
<TouchableOpacity style={ContactStyles.removeButton} onPress={(selectedId) => handleRemoveClick(selectedId)}>
<View><Text style={ContactStyles.removeText}>Remove</Text></View>
</TouchableOpacity>
)
}
})
console.log(selectedId)
return(
<TouchableOpacity style={ContactStyles.addButton} onPress={(selectedId) => handleAddClick(selectedId)}>
<View><Text style={ContactStyles.addText}>Add</Text></View>
</TouchableOpacity>
)
}
// --------------- Rendering and Generating Functions ------------
// -------------------------- Handlers ---------------------------
const handleAddClick = (selectedId) => {
console.log('----------------------------')
console.log(selectedId)
setNewGuests([...newGuests, selectedId])
// console.log(newGuests)
}
const handleRemoveClick = (selectedId) => {
console.log(selectedId)
let newestVersion = []
newGuests.forEach( (guest) => {
if (guest.id !== selectedId){
newestVersion.push(guest)
}
})
setNewGuests(newestVersion)
// console.log(newGuests)
}
// -------------------------- Handlers ---------------------------
if (!loading && queryData){
let allDrivers = [...queryData.driverGetDriversFromDsp.drivers]
return (
<View>
<Banner />
<View>
</View>
<ScrollView contentContainerStyle={ContactStyles.container}>
{renderRoster(allDrivers)}
</ScrollView>
</View>
)
}
else{
return(
<Loading />
)
}
}
export default Contacts
The issue seems to be stemming from the determineAddOrRemove. Right before every possible return value in that function, the uuids come out properly, as shown by the logged statements...
941904b3-77c4-46a4-8cd3-c3d2efbb8459
dd87ed5d-77ed-4ce4-97f4-9e8eca228ce2
31f5922e-8aa8-4ffa-adb4-a4e901b43d3d
add7e664-ec9d-4c51-8e4e-6961e8457b07
713d0da3-9ca5-407c-be1b-fce8bc71d974
03e5e931-154b-44a1-a59c-da5d0de89faa
74ce9746-1998-44f8-9699-3206f2345c88
9e775542-c102-4f66-a597-6d6e53a4587e
0d8d604a-e0bc-4f83-b358-fd6a2fd105a3
cb7cc30e-dda7-41f3-bbb2-641356c55216
f8155be1-f183-4ad2-ba43-2e0b0996ac83
530e363a-564d-4b0a-b1bc-e6eb0ab9554b
aa4fa720-99f1-4ed4-a4a3-7eb57f4eaa6b
b931215d-c59d-4774-8ffe-0ef12ef37532
e4537807-1dda-487a-aecd-ac8afcca6397
ac403235-e207-4452-a09a-6fa9fc6994a5
eaa21ab3-d006-45b0-92fb-bc056c2ec3fb
da2375a9-b014-4dbe-aecd-b946be3b1ad6
fa367846-1d91-4bcf-9288-de96e53e27f9
3ee9f03c-a924-4913-8af0-c9c84fb061f0
721d68c4-a412-4e9b-bea7-a6dddfd96934
a6a7430a-0601-4fb3-b474-6d7e9238c455
ea89422b-190b-4ff8-8e3e-9389c32436a5
7d4b7374-f19f-429d-af0a-e0d5f1c57f24
6961fbeb-4786-4945-98bf-5f49e9e82579
52817972-cfdc-4da1-9c98-a1f0583c49e0
12f2b73d-a9a7-455d-8c2a-db79b5236f3e
9a507278-726a-4e56-9f83-e3eceaa19cfc
46290353-8d4f-4e51-b419-4d78a7f5431c
93ed3e6e-3e60-4c8d-8890-72e27586ce26
6a8d1fc3-68fb-4f80-b92f-701312ec9ad1
248ffde5-edf6-4ed9-9016-d41e16ce09bc
c1f89d3b-ad3c-4118-be5a-73e1317bce8c
e996244a-4b78-46a2-8985-50692c467eec
00308aec-57c0-4f33-98dc-cfd21446cc62
34d3d2c1-a23e-41f2-b0a9-2cabbd4d80bc
495763ef-6ea3-45bb-836a-b75d49a77dca
c445c512-44d8-4004-90fb-9ae41802eda9
18125066-09c9-42f2-acb2-82143c890ad0
3f5ac05d-f111-4ca2-8512-1a802d85d3a9
f36626f9-2cd0-4b7a-b413-09183f4eaa4c
9ffc4980-04d8-4c53-bbdb-3b0615e6a757
2f4917f9-f523-4834-9c58-86c76f2fd462
ccf79ee2-eec7-47b5-853c-3179c0f2df62
55c6d2a0-77ea-4330-88ca-7f1b49a0e891
2c178386-23af-4c35-aa25-d65d4b3237f4
6544ca09-5448-4668-ad8d-2c30d15a7bdb
9ef8ebfc-a850-492e-a717-64340360709f
8ef3b528-e0f3-4058-8410-2bb77eacf322
7d3a4ae7-7d03-4472-b75b-73497e099e3c
c337eb3f-ca38-4932-a530-d9c7edc33619
e5a9cb7f-408b-4dd2-99d4-bc4e17a7a557
cc5f3f92-0854-4a3d-974c-d73ace24b30a
a98feda1-9a33-484e-9cce-b25fdc9765bd
2f290674-be2a-4871-8128-19e5e29341d6
302d07b1-6631-43a2-89f8-78940b794759
d2e745c1-e24c-4b25-a2de-dd73b8de5948
27bf0afd-98ec-45c9-bc94-5393aed6d05e
c0eb9270-74ae-4979-997d-242bf76d288a
6a5a1fb9-b449-49ee-ad0b-d481dbf4d2b9
10309a26-2f7a-4bcc-9214-f16fd6abb418
6113e684-6aa0-4614-8899-9d8740148e29
838875fd-f5ed-4f43-a150-589ad31bc889
a3e088e4-88ad-40c1-acf5-b4f953c80275
b5423188-b5cb-40f7-8e4b-6c69d56fd5bd
But every time I click Add or Remove and trigger the handleAddClick or handleRemoveClick and then consequently trigger the console.log statements in there, the once clean uuid will return this...
Class {
"_dispatchInstances": FiberNode {
"tag": 5,
"key": null,
"type": "RCTView",
},
"_dispatchListeners": [Function onResponderRelease],
"_targetInst": FiberNode {
"tag": 5,
"key": null,
"type": "RCTView",
},
"bubbles": undefined,
"cancelable": undefined,
"currentTarget": ReactNativeFiberHostComponent {
"_children": Array [
ReactNativeFiberHostComponent {
"_children": Array [
ReactNativeFiberHostComponent {
"_children": Array [
3925,
],
"_internalFiberInstanceHandleDEV": FiberNode {
"tag": 5,
"key": null,
"type": "RCTText",
},
"_nativeTag": 3927,
"viewConfig": Object {
"directEventTypes": Object {
"topInlineViewLayout": Object {
"registrationName": "onInlineViewLayout",
},
"topTextLayout": Object {
"registrationName": "onTextLayout",
},
},
"uiViewClassName": "RCTText",
"validAttributes": Object {
"accessibilityActions": true,
"accessibilityHint": true,
"accessibilityLabel": true,
"accessibilityLiveRegion": true,
"accessibilityRole": true,
"accessibilityState": true,
"accessibilityValue": true,
"accessible": true,
"adjustsFontSizeToFit": true,
"allowFontScaling": true,
"collapsable": true,
"dataDetectorType": true,
"disabled": true,
"ellipsizeMode": true,
"importantForAccessibility": true,
"isHighlighted": true,
"maxFontSizeMultiplier": true,
"minimumFontScale": true,
"nativeID": true,
"needsOffscreenAlphaCompositing": true,
"numberOfLines": true,
"onAccessibilityAction": true,
"onAccessibilityEscape": true,
"onAccessibilityTap": true,
"onInlineViewLayout": true,
"onLayout": true,
"onMagicTap": true,
"onTextLayout": true,
"pointerEvents": true,
"renderToHardwareTextureAndroid": true,
"selectable": true,
"selectionColor": true,
"shouldRasterizeIOS": true,
"style": Object {
"alignContent": true,
"alignItems": true,
"alignSelf": true,
"aspectRatio": true,
"backfaceVisibility": true,
"backgroundColor": Object {
"process": [Function processColor],
},
"borderBottomColor": Object {
"process": [Function processColor],
},
"borderBottomEndRadius": true,
"borderBottomLeftRadius": true,
"borderBottomRightRadius": true,
"borderBottomStartRadius": true,
"borderBottomWidth": true,
"borderColor": Object {
"process": [Function processColor],
},
"borderEndColor": Object {
"process": [Function processColor],
},
"borderEndWidth": true,
"borderLeftColor": Object {
"process": [Function processColor],
},
"borderLeftWidth": true,
"borderRadius": true,
"borderRightColor": Object {
"process": [Function processColor],
},
"borderRightWidth": true,
"borderStartColor": Object {
"process": [Function processColor],
},
"borderStartWidth": true,
"borderStyle": true,
"borderTopColor": Object {
"process": [Function processColor],
},
"borderTopEndRadius": true,
"borderTopLeftRadius": true,
"borderTopRightRadius": true,
"borderTopStartRadius": true,
"borderTopWidth": true,
"borderWidth": true,
"bottom": true,
"color": Object {
"process": [Function processColor],
},
"decomposedMatrix": true,
"direction": true,
"display": true,
"elevation": true,
"end": true,
"flex": true,
"flexBasis": true,
"flexDirection": true,
"flexGrow": true,
"flexShrink": true,
"flexWrap": true,
"fontFamily": Object {
"process": [Function processFontFamily],
},
"fontSize": true,
"fontStyle": true,
"fontVariant": true,
"fontWeight": true,
"height": true,
"includeFontPadding": true,
"justifyContent": true,
"left": true,
"letterSpacing": true,
"lineHeight": true,
"margin": true,
"marginBottom": true,
"marginEnd": true,
"marginHorizontal": true,
"marginLeft": true,
"marginRight": true,
"marginStart": true,
"marginTop": true,
"marginVertical": true,
"maxHeight": true,
"maxWidth": true,
"minHeight": true,
"minWidth": true,
"opacity": true,
"overflow": true,
"overlayColor": Object {
"process": [Function processColor],
},
"padding": true,
"paddingBottom": true,
"paddingEnd": true,
"paddingHorizontal": true,
"paddingLeft": true,
"paddingRight": true,
"paddingStart": true,
"paddingTop": true,
"paddingVertical": true,
"position": true,
"resizeMode": true,
"right": true,
"rotation": true,
"scaleX": true,
"scaleY": true,
"shadowColor": Object {
"process": [Function processColor],
},
"shadowOffset": Object {
"diff": [Function sizesDiffer],
},
"shadowOpacity": true,
"shadowRadius": true,
"start": true,
"textAlign": true,
"textAlignVertical": true,
"textDecorationColor": Object {
"process": [Function processColor],
},
"textDecorationLine": true,
"textDecorationStyle": true,
"textShadowColor": Object {
"process": [Function processColor],
},
"textShadowOffset": true,
"textShadowRadius": true,
"textTransform": true,
"tintColor": Object {
"process": [Function processColor],
},
"top": true,
"transform": Object {
"process": [Function processTransform],
},
"transformMatrix": true,
"translateX": true,
"translateY": true,
"width": true,
"writingDirection": true,
"zIndex": true,
},
"testID": true,
"textBreakStrategy": true,
},
},
},
],
"_internalFiberInstanceHandleDEV": FiberNode {
"tag": 5,
"key": null,
"type": "RCTView",
},
"_nativeTag": 3929,
"viewConfig": Object {
"Commands": Object {},
"bubblingEventTypes": Object {
"topAssetDidLoad": Object {
"phasedRegistrationNames": Object {
"bubbled": "onAssetDidLoad",
"captured": "onAssetDidLoadCapture",
},
},
"topBlur": Object {
"phasedRegistrationNames": Object {
"bubbled": "onBlur",
"captured": "onBlurCapture",
},
},
"topChange": Object {
"phasedRegistrationNames": Object {
"bubbled": "onChange",
"captured": "onChangeCapture",
},
},
"topEndEditing": Object {
"phasedRegistrationNames": Object {
"bubbled": "onEndEditing",
"captured": "onEndEditingCapture",
},
},
"topFocus": Object {
"phasedRegistrationNames": Object {
"bubbled": "onFocus",
"captured": "onFocusCapture",
},
},
"topKeyPress": Object {
"phasedRegistrationNames": Object {
"bubbled": "onKeyPress",
"captured": "onKeyPressCapture",
},
},
"topPress": Object {
"phasedRegistrationNames": O...(truncated to the first 10000 characters)
I tried changing the name of the variables, nothing. When I put a static value into the function (for example changing handleAddClick(selectedId) to handleAddClick("1234") it will print what I expect, in this case 1234 But any variable I put in instantly gets its value changed to that big mess I just showed above. Has anyone experienced something like this in the past and/or have any ideas on how to fix this?

The parameter passed by Touchable into the onPress function is a GestureResponderEvent. You are renaming it to selectedId, and then consequently adding it to your list.
onPress={(selectedId) => handleAddClick(selectedId)
You probably mean onPress={() => handleAddClick(selectedId), but you haven't shown where selectedId comes from so I can't say for sure.

Related

Vuelidate nested validations - vuelidate object only includes the last component's validations

I am attempting to use Vuelidate nested validations, but I am surely missing something.
I have a simple component that only contains an input, and a validation making that input required.
<template>
<input type="text" v-model="value" />
</template>
<script>
import useVuelidate from "#vuelidate/core";
import { required } from "#vuelidate/validators";
export default {
name: "MyInput",
setup() {
return { v$: useVuelidate() };
},
props: {
modelValue: String,
},
computed: {
value: {
get() {
return this.modelValue;
},
set(value) {
this.$emit("update:modelValue", value);
},
},
},
validations() {
return {
value: { required },
};
},
};
</script>
And my app just includes two instances of this component, and prints the Vuelidate object for my inspection.
<template>
<pre>{{ v$ }}</pre>
<my-input v-model="myValue1"></my-input>
<br />
<my-input v-model="myValue2"></my-input>
</template>
<script>
import useVuelidate from "#vuelidate/core";
import MyInput from "./components/my-input.vue";
export default {
name: "App",
components: {
MyInput,
},
setup() {
return { v$: useVuelidate() };
},
data() {
return {
myValue1: "",
myValue2: "",
};
},
};
</script>
<style scoped>
</style>
This is what's getting printed:
{
"$dirty": false,
"$path": "__root",
"$model": null,
"$error": false,
"$errors": [],
"$invalid": true,
"$anyDirty": false,
"$pending": false,
"$silentErrors": [
{
"$propertyPath": "value",
"$property": "value",
"$validator": "required",
"$uid": "value-required",
"$message": "Value is required",
"$params": {
"type": "required"
},
"$response": false,
"$pending": false
}
],
"$validationGroups": {},
"_vuelidate_undefined": {
"$dirty": false,
"$path": "__root",
"$model": null,
"$error": false,
"$errors": [],
"$invalid": true,
"$anyDirty": false,
"$pending": false,
"$silentErrors": [
{
"$propertyPath": "value",
"$property": "value",
"$validator": "required",
"$uid": "value-required",
"$message": "Value is required",
"$params": {
"type": "required"
},
"$response": false,
"$pending": false
}
],
"$validationGroups": {},
"value": {
"$dirty": false,
"$path": "value",
"required": {
"$message": "Value is required",
"$params": {
"type": "required"
},
"$pending": false,
"$invalid": true,
"$response": false
},
"$externalResults": [],
"$invalid": true,
"$pending": false,
"$error": false,
"$silentErrors": [
{
"$propertyPath": "value",
"$property": "value",
"$validator": "required",
"$uid": "value-required",
"$message": "Value is required",
"$params": {
"type": "required"
},
"$response": false,
"$pending": false
}
],
"$errors": [],
"$model": "",
"$anyDirty": false
}
}
}
Only the second input component is showing up- updating the second input makes the data update, but not the first one. Also note the property "_vuelidate_undefined" which looks like something went wrong. Is some sort of key missing on my components? Am I supposed to namespace the properties I'm validating somehow?
Sandbox with this code can be found here.

Disable the pagination navigation buttons during an API request in AG Grid

How could I disable the pagination navigation buttons during an API request in AG Grid? I am using Vue.js if it matters.
E.g. here I would like to disable the controls while the API request is in progress. How could I do that?
var checkboxSelection = function (params) {
// we put checkbox on the name if we are not doing grouping
return params.columnApi.getRowGroupColumns().length === 0;
};
var headerCheckboxSelection = function (params) {
// we put checkbox on the name if we are not doing grouping
return params.columnApi.getRowGroupColumns().length === 0;
};
const columnDefs = [
{
field: 'athlete',
minWidth: 170,
checkboxSelection: checkboxSelection,
headerCheckboxSelection: headerCheckboxSelection,
},
{ field: 'age' },
{ field: 'country' },
{ field: 'year' },
{ field: 'date' },
{ field: 'sport' },
{ field: 'gold' },
{ field: 'silver' },
{ field: 'bronze' },
{ field: 'total' },
];
var autoGroupColumnDef = {
headerName: 'Group',
minWidth: 170,
field: 'athlete',
valueGetter: (params) => {
if (params.node.group) {
return params.node.key;
} else {
return params.data[params.colDef.field];
}
},
headerCheckboxSelection: true,
// headerCheckboxSelectionFilteredOnly: true,
cellRenderer: 'agGroupCellRenderer',
cellRendererParams: {
checkbox: true,
},
};
const gridOptions = {
defaultColDef: {
editable: true,
enableRowGroup: true,
enablePivot: true,
enableValue: true,
sortable: true,
resizable: true,
filter: true,
flex: 1,
minWidth: 100,
},
suppressRowClickSelection: true,
groupSelectsChildren: true,
// debug: true,
rowSelection: 'multiple',
rowGroupPanelShow: 'always',
pivotPanelShow: 'always',
enableRangeSelection: true,
columnDefs: columnDefs,
paginationAutoPageSize: true,
pagination: true,
autoGroupColumnDef: autoGroupColumnDef,
};
// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function () {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
.then((response) => response.json())
.then((data) => gridOptions.api.setRowData(data));
});
I found the example above in the documentation.

Cannot read property 'dataSets' of undefined

I always get this error when I update the line chart data. I know that setState is wrong, but the specific modification method cannot be found, and ask for help. Thank you.
I think it's the problem, but there's no solution.
this.setState({
data: {
...this.state.data.$set,
dataSets:[{
...this.state.data.$set.dataSets[0],
values
}]
},
xAxis: {
...this.state.xAxis.$set.valueFormatter,
valueFormatter,
axisMaximum,
axisMaximum
},
})
Chart github address:
https://github.com/wuxudong/react-native-charts-wrapper
This is the source code, just uploaded the picture, the feeling is not suitable for reading.
componentDidMount() {
this.setState(
update(this.state, {
data: {
$set: {
dataSets: [{
values: [{y: 10}, {y: 20}, {y: 30.11}, {y: 25.77}],
label: 'LineChart',
config: {
lineWidth: 0.5,
drawCircles: false,
highlightColor: processColor('red'),
color: processColor('red'),
drawFilled: true,
fillColor: processColor('red'),
fillAlpha: 60,
valueTextSize: 15,
valueFormatter: "##.000",
}
}],
}
},
xAxis: {
$set: {
fontFamily:"HelveticaNeue-Medium",
fontWeight:"bold",
fontStyle:"italic",
valueFormatter: ['2017-01-01 10:00:000','2017-02-01 10:00:000','2017-03-01 10:00:000'],
position: 'BOTTOM' ,
drawGridLines: false
}
},
yAxis: {
$set: {
left: {
drawLabels: true,
drawAxisLine: true,
drawGridLines: false,
drawValueAboveBar:false,
zeroLine: {
enabled: true,
lineWidth: 1
}
},
right: {
enabled: false
}
}
},
})
);
}
componentWillReceiveProps(nextProps) {
debugger;
if (nextProps.zxData !== this.props.zxData) {
let values=[];
let valueFormatter=[];
let axisMaximum=nextProps.zxData.length;
nextProps.zxData.map((item,key)=>{
values.push({y:item.YValue});
valueFormatter.push(item.XValue);
})
this.setState({
data: {
...this.state.data.$set,
dataSets:[{
...this.state.data.$set.dataSets[0],
values
}]
},
xAxis: {
...this.state.xAxis.$set.valueFormatter,
valueFormatter,
axisMaximum,
axisMaximum
},
})
}
}

Add object to array in Redux?

I'm trying to add a element to a array, which is called allLogbooks. This array contains objects called Logbook. My issue is, how do I fit in code so that it adds the new element to the array which is declared in my reducer? This is my initial state:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
This is my reducer:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
And this is my action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
I then make a POST call to a nodejs server, where it will respond with a message if it was successful, and the logbook which was just created. the following data is what it returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
I then dispatch in the API call, as such:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
I've substituted this by using AsyncStorage to access the array abroad all my views, but I know this is wrong.
I am struggling a little to comprehend your question so I've tried my best. Please let me know if I'm completely off with my answer.
Your reducer:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
Your action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}

Server-based DataTables + YADCF with AJAX-based select2: selecting option clears Select2 selection

The set-up:
DataTables is using remote data with pagination (AJAX-based)
YADCF is using a Select2 that's grabbing options using AJAX call
Selecting Select2 option triggers grid refresh and filtering (everything is correct)
The problem:
Right after DataTables pulls the updated rowset, YADCF re-runs its intialization routine and Select2 loses its state (i.e. the selected option is no longer selected and is not in the DOM anymore).
This:
becomes this after grid reloads (select2 control re-initialized and lost all options pulled via AJAX, including the one that was selected):
How can I avoid YADCF re-initialization in such case?
Having debugged the problem for a while I found that function appendFilters(...) is called after each grid refresh from this YADCF line:
https://github.com/vedmack/yadcf/blob/master/jquery.dataTables.yadcf.js#L3332
which, in turn is fired by DataTables' draw event.
Thanks!
EDIT:
DataTables config array:
var dataTableConfig = {
"autoWidth": false,
"deferLoading": 220,
"pageLength": 5,
"searchDelay": 0,
"searching": true,
"placeholder": null,
"ordering": true,
"paging": true,
"info": true,
"columns": [
{
"name": "company",
"data": {
"_": "company",
"filter": "company",
"display": "company"
},
"visible": true,
"searchable": true,
"orderable": true,
"className": "column_Company"
}
],
"showGlobalSearch": true,
"enableColumnFilter": true,
"columnFilterPosition": "table",
"resetPaging": true,
"select": {
"style": "single"
},
"serverSide": true,
"ajax": {
"url": "/datasource/",
"type": "post"
}
};
YADCF INIT:
colCfg = [
{
"column_number": 2,
"filter_type": "select",
"data": [],
"filter_default_label": "(select..)",
"enable_auto_complete": false,
"sort_as": "alpha",
"sort_order": "asc",
"filter_match_mode": "contains",
"exclude_label": "exclude",
"select_type": "select2",
"select_type_options": {
"width": "300",
ajax: {
url: '/datasource/',
dataType: 'json',
method: 'post',
delay: 750,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.results,
pagination: {
more: (params.page * 20) < data.total_count
}
};
},
cache: true
},
minimumInputLength: 1,
templateResult: formatItem,
templateSelection: formatItemSelection,
escapeMarkup: function(v) {return v;}
},
"case_insensitive": true,
"filter_delay": 500
}
];
yadcf.init(dataTable, colCfg);