Home > Net >  React Native with hooks, Modal not updating on state change unless I close and reopen
React Native with hooks, Modal not updating on state change unless I close and reopen

Time:02-16

The only other similar question I could find here involved redux which I'm not familiar with. I don't have a lot of code, I'd like a simple Filter to pop up with a list of stores represented by checkboxes. It seems to work when I console.log to see my object state, except that the checkboxes don't visibly show a change until I close and then reopen the modal. Perhaps I'm misunderstanding how modals or state works. Example: I check box 1 and console log shows the state changed but the box still looks unchecked. I close the modal and reopen, box 1 is now checked.

import React, { useState } from "react";
import {
  Button,
  FlatList,
  Modal,
  StyleSheet,
  TouchableOpacity,
  View,
} from "react-native";
import AppText from "./AppText";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import colors from "../config/colors";
import { CheckBox } from 'react-native-elements';

function FilterPicker({
  filterStores,
  setFilterStores,
}) {
  const [modalVisible, setModalVisible] = useState(false);

  function onCheckChanged(id) {
    const index = filterStores.findIndex(x => x.id === id);
    filterStores[index].checked = !filterStores[index].checked;
    setFilterStores(filterStores);
    console.log(JSON.stringify(filterStores));
  }

  return (
    <>
      <TouchableOpacity onPress={() => setModalVisible(true)}>
        <View style={styles.Filter}>
          <MaterialCommunityIcons
            name="tune"
            color={colors.black}
            size={30}
            style={styles.Icon}
          />
        </View>
      </TouchableOpacity>
      <Modal visible={modalVisible} onRequestClose={()=> setModalVisible(false)} animationType="slide">
        <View>
            {
                filterStores.map((item,key) => <CheckBox title={item.key} key={key}  checked={item.checked} onPress={()=>onCheckChanged(item.id)}/>)
            }
        </View>
      </Modal>
    </>
  );
}

export default FilterPicker;

CodePudding user response:

In my opinion, because the state doesn't change so it doesn't re-render

CodePudding user response:

try after modifying your onCheckChanged function like following.
you are mutating filterStores

function onCheckChanged(id) {
    const index = filterStores.findIndex(x => x.id === id);
    const newFilterStores = [...filterStores];
    newFilterStores[index] = {...newFilterStores[index],checked:!newFilterStores[index].checked};
    setFilterStores(newFilterStores);
    console.log(JSON.stringify(newFilterStores));
  }
  • Related