Home > Software engineering >  NextJS, Typescript -> Write Data to Google Cloud Firestore Map (nested object)
NextJS, Typescript -> Write Data to Google Cloud Firestore Map (nested object)

Time:01-01

I need your help. I am writing an application with NextJS(React), Typescript and Google Cloud Firestore. So far it works without any problems. However, I want to store the address and phone in a nested object in Firestore (Map). This is also created correctly in Firestore via my variables. I can access and set all variables in my inputs. Except the one from my nested object. I have tried many versions, but unfortunately I can't find the right solution. How can I access these variables in the "address" object in my form element in return (street, state, zip, etc) to set them.

My variables

const [formInput, setFormInput] = useState({
name: "",
description: "",
adress: {
  street: "",
  zip: 0,
  city: "",
  state: ""
},
phone: {
  phoneNumber: "",
  mobilePhoneNumber: "",
},
taxId: "",
generetedBy: currentUser.uid,
dateExample: serverTimestamp(),
//stringExample: "",
//booleanExample: true,
//numberExample: 3.14159265,
//arrayExample: [5, true, "hello"],
//nullExample: null,

});

My Submit Handler

const handleSubmit = async (e: any) => {
e.preventDefault();

const colRef = collection(db, "restaurant");

await addDoc(colRef, formInput);

//formRef.current.reset()

};

My TextInput

<TextInput
      onChange={(e: any) =>
        setFormInput({
          ...formInput,
          adress.street: e.target.value,
        })
      }
      type="text"
      name="street-address"
      id="street-address"
      autoComplete="street-address"
      //value={formInput.adress.street}
    />

There i get an Error for "adress.street". This will not work as i was thinking... Can you help me?

CodePudding user response:

set like this

setFormInput({
      ...formInput,
      adress :{
         ...formInput.address,
         street: e.target.value,
     }
})
  • Related