Home > Software design >  Reset Select Item - React Native
Reset Select Item - React Native

Time:01-09

I have a form which includes a select dropdown (items are populated via an api call). When I leave the screen I would like to be able to reset this back to it's initial state (Default state is a placeholder - Select Event)

I can clear text and textarea inputs within a useFocusEffect() but struggling with understanding how to reset a select dropdown

To reset the select dropdown i have tried setEventTypeData([]); but when navigating back to the screen, the last selected option is still selected (text inputs have been cleared though)

export const CreateNewEvent = ({navigation}) => {
  const globalContext = useContext(AppContext);
  const userId = globalContext.userInfo.id;
  // dropdown populated with this
  const [eventTypeData, setEventTypeData] = useState([]);
  const [newEventDescription, setEventDescription] = useState('');
  const [newEventLimit, setEventLimit] = useState(0);

  const clearFormData = () => {
    setEventTypeData([]); // tried setting back to original state but does not work
    setEventDescription('');
    setEventLimit(0);
  };

  useFocusEffect(
    React.useCallback(() => {
      const body = JSON.stringify({userId});
      fetch(eventTypesUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: body,
      })
      .then(response => response.json())
      .then(json => setEventTypeData(json))
      .catch(error => console.error(error))
      .finally(() => setLoading(false));

    return () => {
      // Run logic when the user leaves screen,
      // Clear form
      clearFormData();
    };
  }, [userId]),
);

// Select Dropdown
{/* Event Name Select Field */}
<FormControl isRequired isInvalid={'eventName' in errors}>
  <FormControl.Label>Select Event</FormControl.Label>
  <Select
    onValueChange={newEventName =>
    updateEventNameAndDescription(newEventName)
  }
    placeholder="Select Event"
    {eventTypeData.map(event => (
      <Select.Item
        key={event.id}
        label={event.name}
        value={event.name}
       />
     ))}
  </Select>
}

How can i ensure that when navigating back to this screen that the Select dropdown is reset to its original state

Thanks

CodePudding user response:

I rewrite your example. I hope this help. You forget to unsubscribe from API call

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

  const isFocused = useIsFocused();

  useEffect(() => {
    if (!isFocused) {
      clearFormData()
    }
  }, [isFocused]);

  useFocusEffect(
    React.useCallback(() => {
      const body = JSON.stringify({ userId });
      const unsubscribe = fetch(eventTypesUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: body,
      })
        .then((response) => response.json())
        .then((json) => setEventTypeData(json))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));

      return () => unsubscribe();
      };
    }, [userId]),
  );

CodePudding user response:

    export const CreateNewEvent = ({navigation}) => {
    const globalContext = useContext(AppContext);
    const userId = globalContext.userInfo.id;
    // dropdown populated with this
    const [eventTypeData, setEventTypeData] = useState([]);
    const [newEventDescription, setEventDescription] = useState('');
    const [newEventLimit, setEventLimit] = useState(0);

    const [selectedEventName, setSelectedEventName] = useState(); 
  
    const clearFormData = () => {
        setSelectedEventName(); 
        setEventDescription('');
        setEventLimit(0);
      };

    useEffect(() => {
        selectedEventName ? updateEventNameAndDescription(selectedEventName) : clearFormData();

    }, [selectedEventName])
  
    useFocusEffect(
      React.useCallback(() => {
        const body = JSON.stringify({userId});
        fetch(eventTypesUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
          },
          body: body,
        })
        .then(response => response.json())
        .then(json => setEventTypeData(json))
        .catch(error => console.error(error))
        .finally(() => setLoading(false));

      return () => {
        // Run logic when the user leaves screen,
        // Clear form
        clearFormData();
      };
    }, [userId]),
  );
  
  // Select Dropdown
  {/* Event Name Select Field */}
  <FormControl isRequired isInvalid={'eventName' in errors}>
    <FormControl.Label>Select Event</FormControl.Label>
    <Select
      value={selectedEventName}
      onValueChange={newEventName =>
        setSelectedEventName(newEventName)
    }
      placeholder="Select Event"
      {eventTypeData.map(event => (
        <Select.Item
          key={event.id}
          label={event.name}
          value={event.name}
         />
       ))}
    </Select>
  }
  •  Tags:  
  • Related