I'm using a multiple selection list to React Native. It is react-native-sectioned-multi-select.
I used it to input data to form. When inserting data using the selection list, it works fine. No problem. Now, I need to edit form. So, when I load the form, it does not load selected items to the selection list. I used onSelectedItemsChange to load data. But, I'm getting an error. Instead of automatically calling that function, if I call the function using a button, it loads selected items. But, I need to do it without manually clicking a button.
Here is my code regarding the multiple select.
<SectionedMultiSelect items={this.state.items} uniqueKey="id" subKey="subItem" selectText="Select" confirmText="Select" searchPlaceholderText="Search" removeAllText="Clear all" showDropDowns={true} readOnlyHeadings={true} showCancelButton={true} showRemoveAll={true} onSelectedItemsChange={this.onSelectedItemsChange} selectedItems={this.state.selectedItems}
onSelectedItemsChange = (selectedItems) => { this.setState({ selectedItems});
};When I try to automatically setState of selectedItems it gives the error. But, if I set the state of selectedItems by a button press, it works and selected items are displayed.
Can anyone help me in this case?
onSelectedItemsChange 2 1 Answer
You need to save the items in async storage. When you edit the form get the items storage and add them to selectedItems array.
for example
storage.js
// create function for saving items to storage
export const SaveItem = async (key, value) => { try { await AsyncStorage.setItem(key, value); console.log('saved'); } catch (e) { console.log(e); }
};
// create function for saving items to storage
export const ReadItem = async key => { try { var result = await AsyncStorage.getItem(key); return result; } catch (e) { return e; }
};and use the functions to read and save data, using each forms name as a key. like SaveItem('form1', [23,34,45]). Import the functions in your components.
import { SaveItem, ReadItem } from './storage';
// get items for a form
editForm = key => { ReadItem(key).then(res => { const selected = JSON.parse(result); this.setState({ selectedItems: selected }); });
};
// save form data using each forms name
saveItems = (key, value) => { const items = JSON.stringify(value); SaveItem(key, items) .then(res => { console.log('saved', res); }) .catch(e => console.warn(e));
}; 5