Home > Software design >  how to refresh the list after submitting a form in react-native?
how to refresh the list after submitting a form in react-native?

Time:02-17

when redirecting to index screen after submitting a post-form, the index screen does not show the newly added item in the list, can anyone help? here is my Customer.js page

export default function Customer({ navigation }) {
  const [customers, setCustomers] = useState([]);
  const [isLoading, setLoading] = useState(true);    
const getCustomers = async () => {
    try {
      const response = await fetch("http://localhost:3001/api/customers");
      const json = await response.json();
      setCustomers(json);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getCustomers();
  }, []);
return (
    <View style={styles.item}>
      <TouchableOpacity
        onPress={() => navigation.navigate("AddCustomer")}
        style={styles.btn}
      >
        <Text style={styles.btnText}>Add New Customer</Text>
      </TouchableOpacity>
      <FlatList
        data={customers}
        extraData={customers}
        renderItem={({ item }) => (
          <TouchableOpacity
            onPress={() => navigation.navigate("CustomerDetails", item)}
          >
            <Text style={styles.item}>{item.name}</Text>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item._id}
      />
    </View>
  );
}

}

and here is my AddCustomer.js page

const AddCustomer = ({ navigation, route }) => {
  const [name, setName] = useState("");
  const [phone, setPhone] = useState(0);
  const [isGold, setIsGold] = useState(false);

  const handleSubmit = async () => {
    // e.preventDefault();
    return await fetch("http://localhost:3001/api/customers", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: name,
        phone: phone,
        isGold: isGold,
      }),
    }).then(() => {
      navigation.navigate("Customer", { customers: [name, phone, isGold] });
    });
  };

  return (
    <View>
      <Text style={styles.title}>Add New Customer</Text>
      <View>
        <TextInput
          style={styles.input}
          onChangeText={(val) => setName(val)}
          value={name}
          placeholder="Your name"
          onBlur={Keyboard.dismiss}
        />
        <TextInput
          style={styles.input}
          onChangeText={(val) => setPhone(val)}
          value={phone}
          placeholder="phone number"
        />
        <TextInput
          style={styles.input}
          onChangeText={(val) => setIsGold(val)}
          value={isGold}
          placeholder="is gold member"
          autoCorrect={false}
          autoCapitalize={false}
        />
      </View>

      <View style={styles.inputContainer}>
        <TouchableOpacity style={styles.saveButton} onPress={handleSubmit}>
          <Text style={styles.saveButtonText}>Add Customer</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

new customer would be added and everything else work fine but the Customer page does not get re-rendered or refresh or reload.

CodePudding user response:

In your Customer.js do it like below -

useEffect(() => {
  const unsubscribe = navigation.addListener('focus', async () => {
    getCustomers();
  }

return unsubscribe ;
}, [navigation]);

CodePudding user response:

import { useFocusEffect } from '@react-navigation/native';

 useFocusEffect(
      React.useCallback(() => {
        // Do something when the screen is focused
         getCustomers();
        return () => {
          // Do something when the screen is unfocused
        };
      }, []),
    );
  • Related