Reactjs firebase convert string to map

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.

Reactjs firebase convert string to map

Reactjs firebase convert string to map.

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>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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,
    }
  });
};

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply