What is the correct way to use push array in React native ?
const BuilderIndicatorCard = (props) => {
const [isChecked, setIsChecked] = useState(false);
const [checkedValue, setCheckedValue] = useState([]);
let storeCheckedValue = [];
useEffect(() => {
if (isChecked) {
storeCheckedValue.push(props.indicator);
}
console.log(storeCheckedValue);
}, [isChecked, checkedValue])
// const removeCheckedStrategy = (checkedValue, array) => {
// var copyArray = [...array];
// var index = copyArray.indexOf(checkedValue);
// if (index !== -1) {
// copyArray.splice(index, 1);
// setArray(copyArray);
// }
// }
return (
<CheckBox
containerStyle={styles.checkbox}
size={15}
textStyle={styles.name}
title={props.indicator}
checked={isChecked}
onPress={() => {setIsChecked(!isChecked)}}
/>
);
};
When I do storeCheckedValue.push(props.indicator); why the array keep replace and not append ?
This is show in the console :
Array [
"Price Below MA (5)",
]
Array [
"Price Below MA (7)",
]
Array [
"Price Below MA (9)",
]
did I miss something in here ?
I found a proper way to solve my question above. This is how I did it.
I use redux-toolkit
Create a slice like :
import { createSlice } from '@reduxjs/toolkit'
const addChecked = (state, action) => {
state.indicator = [...state.indicator, action.payload];
}
const removeChecked = (state, action) => {
state.indicator = state.indicator.filter(data => data != action.payload);
}
// status: 'idle' | 'loading' | 'succeeded' | 'failed',
export const BuilderSlice = createSlice({
name: 'Builder',
initialState: {
indicator: [],
status: 'idle',
error: null
},
reducers: {
addCheckedIndicator: addChecked,
removeCheckedIndicator: removeChecked
},
extraReducers: {
}
});
export const { addCheckedIndicator, removeCheckedIndicator } = BuilderSlice.actions
Then In the card component I change to like this :
import { addCheckedIndicator, removeCheckedIndicator } from '../redux/slice/builder/BuilderSlice';
const BuilderIndicatorCard = (props) => {
const dispatch = useDispatch();
const data = useSelector(state => state.Builder.indicator);
const [isChecked, setIsChecked] = useState(true);
const addValue = useCallback(() => {
setIsChecked(!isChecked);
if (isChecked) {
dispatch(addCheckedIndicator(props.indicator));
} else {
dispatch(removeCheckedIndicator(props.indicator));
}
}, [isChecked]);
return (
<CheckBox
containerStyle={styles.checkbox}
size={15}
textStyle={styles.name}
title={props.indicator}
checked={props.checked}
onPress={() => {addValue()}}
/>
);
};
I dispatch the function in slice in here:
dispatch(addCheckedIndicator(props.indicator));
dispatch(removeCheckedIndicator(props.indicator));
And then make sure use :
const addValue = useCallback(() => {
},[second]);
Not useEffect.