This would be my first time of doing this and I can't seem to find a way around it. I would like to persist check box state in react.js and would like this to be done without my MongoDB database. Here are my codes so far: I am fetching list of subscribers from my MongoDB database like this:
const [allSubscribers, setAllSubscribers] = useState([]);
const response = await axiosPrivate.get(`${BASE_URL}/emailsub/subscribers?page=${pageNumber})
setAllSubscribers(response.data)
This displays 9 subscribers per page. On next page, a new API call is made and another 9 subscribers listed, until the last set of items. That is how I handled the pagination via query.
To create the input checkbox, I had to create another array based on the size of the subscribers fetched from the database.
const [checkedState, setCheckedState] = useState();
const totalPosts = allSubscribers.length // to get the length of the items fetched from database
const fillArray = new Array(totalPosts).fill( false)//created new array and fill it with initial value of `false`
//useEffecct to set the check state whenever the all subscriber state changes
useEffect(()=>{
setCheckedState(fillArray)
}, [allSubscribers])
When the checkbox is clicked it returns the opposite of the value of the matched item. And the subscriber Id is passed into an array which is a state called const [selectedSubscriberId, setSelectedSubscriberId] = useState([]);
const arrayOfSelectedPostId = (subscriberId, indexPosition) =>{
setSelectedSubscriberId(prevArray => [...prevArray, subscriberId]);
const updatedCheckedState = checkedState.map((item, index) =>
index == indexPosition ? !item : item
)
setCheckedState(updatedCheckedState);
}
When unchecked, I removed the matched subscriberId from the selectedSubscriberId array.
//handle deselecting of a selected postid
const handleChangeState = (subscriberId)=>{
selectedSubscriberId.map((item)=>{
console.log(item === subscriberId)
if(item === subscriberId){
const newArray = selectedSubscriberId.filter((item) => item !==subscriberId)
setSelectedSubscriberId(newArray);
}
})
};
This is the checkbox input:
<input type="checkbox" id={index} checked={checkedState[index]} onChange={()=>{arrayOfSelectedPostId(subscriberId, index); handleChangeState(subscriberId)}}/>
On page load or refresh, I want to check the selectedSubscriberId array and any subscriber id found there should remain checked. Is there a way I can handle this? I don't mind reworking the code if possible.