Modified state for showing the AddModal to have an additional property for data, which is passed in if there is an object to edit
// manages the state to determine if we need to open// the modal or notconst[showModal,setShowModal]=useState<{show:boolean;initialData?:IModalData;}>({show:false});
React Hook Form provides an easy way to set defaultData and it also has a provider to get access to the required functions to properly create components to structure your forms better.
3) The modal is wrapped with the ReactHookForm FormProvider and the methods, properties associated with the form are passed as parameters. This give us access to the information in the child components without passing properties down through the component hierarchy.
4) Access default values in my custom component, since I set the default values when creating the form, the default values will be matched to the IonInput element with the matching name when rendered in MyIonTextItem
// MyIonTextItem.tsxconst{control,errors,register}=useFormContext();...<IonItem><IonLabel>{labelName}</IonLabel><Controllerrender={({onChange})=>(<IonInputtype="text"name={name}ref={register}onIonChange={onChange}/>)}control={control}name={name}rules={{required:labelName+" is a required field",}}/></IonItem>
Changes to addSomething function where we determine if there is an id, then we will update the item in the database if not, we will add the item
Firebase update needed in the DataContext.tsx file to exposed the new function. Since we are using typescript lets add it to the interface IState first.
interfaceIState{dataCollection:null|undefined|any;// NEW function for updating itemsupdateItem:(itemData:IModalData)=>Promise<void>;addItem:(itemData:IModalData)=>Promise<void>;removeItem:(itemData:IModalData)=>Promise<void>;}
// the store objectletstate={dataCollection:data,addItem,updateItem,// <-- NEWremoveItem,};// wrap the application in the provider with the initialized contextreturn<DataContext.Providervalue={state}>{children}</DataContext.Provider>;
New Code for rendering the list with the Line component extracted and all the functions passed in.
The new functionality of editing an item is triggered by clicking on the item in the list.
We created a separate stateless component that just renders the line items and calls appropriate functions when the line is clicked or the delete button on the line is clicked
I am starting to integrated typescript into my examples since I am seeing questions about types popping up in the forums. The IModalData is the structure of the data that is written to…