Home > OS >  Reactjs firebase convert string to map
Reactjs firebase convert string to map

Time:08-06

In my app in reactjs i have created an array steps, where the user can add the steps to prepare a recipe and it will be stored in firebase, my problem is the steps are being stored directly as strings in the array, what i want is them to be stored inside a map. Can someone please tellme how to do this.

steps firebase

map firebase.

I want them to be like this.

Code :

const [form, setForm] = useState({
steps: []
})

addDoc(recipesCollectionRef, form)

setForm({
  steps: []
})
const handleStep = (e, i) => {
const stepsClone = [...form.steps]

stepsClone[i] = e.target.value

setForm({
  ...form,
  steps: stepsClone
})
}

const handleStepCount = () => {
setForm({
  ...form,
  steps: [...form.steps, ""]
})
}
<label>Steps</label>
          {
            form.steps.map((step, i) => (
              <textarea 
                type="text"
                key={i}
                value={step} 
                onChange={e => handleStep(e, i)} />
            ))
          }
          <button type="button" onClick={handleStepCount}>Add step</button>

CodePudding user response:

e.target.value is a string. The current code appears to be saving an array of strings with stepsClone[i] = e.target.value. If you want to save an array of objects then the code needs to do something a little different.

Example:

const handleStep = (e, i) => {
  setForm(form => {
    const stepsClone = [...form.steps];

    stepsClone[i] = {
      from: e.target.value,
      to: // another value ???
    };

    return {
      ...form,
      steps: stepsClone,
    }
  });
};
  • Related