0

const [workout,setWorkout] = useState({
      workoutname:"",
      exercisesSelection:[],
    });
    
const SaveWorkout = async ()=>{
      setWorkout(prevArr=>{
        return {
          ...prevArr,
          workoutname:workoutName,
          exercisesSelection:currentExercises
        }
      })
      console.log(workout)
      await addDoc(workoutsCollectionRef,{
        workoutName:workout.workoutname,
        exercises:workout.exercisesSelection,
      })
      
    }

Documment is being added with the values empty. I believe that the state is changing after the addDoc.

enter image description here

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • *I believe that the state is changing after the addDoc.* - that is certainly the case. Do you have a question about that? Seems like you should not use the state variable in `SaveWorkout` and instead use the correct values. – Doug Stevenson Jul 10 '23 at 21:15
  • How can i set the state before running the addDoc? – Francisco Soares Jul 10 '23 at 21:19
  • Is that absolutely the requirement here, or would it be enough to call addDoc with the correct values (assuming they are what you expect in `workoutName` and `currentExercises`? Please edit the question to clarify - don't leave information only in comments.\ – Doug Stevenson Jul 10 '23 at 21:22

1 Answers1

1

Setting state is an asynchronous operation in ReactJS. If you have an operation that should only run after the state has been modified, use a (separate) useEffect hook for it. So something like:

useEffect(() => {
  await addDoc(workoutsCollectionRef,{
    workoutName:workout.workoutname,
    exercises:workout.exercisesSelection,
  }), 
  [workout] //  ensure the code runs whenever workout has changed
);

Note that this is not related to the specific Firebase version, and would be the same in SDK versions 8 and before

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807