0

I'm creating dogs list app using React Hooks and Firebase. There's a list of dogs, and this page will be a detail page of each dogs.

So far I've successfully fetched an object from firebase database. Now I'm trying to put that object in state using setDog()

const [dog, setDog] = useState([{ name: '', breed: '' }]);

useEffect(() => {

  const db = firebase.firestore();
  var docRef = db.collection("dogs").doc(id); // id is the one I click from dogs list

  docRef.get()
    .then(response => {
        const newDog = response.data();
        console.log("newDog", newDog); // Object {name: 'cookie', breed: 'beagle'}
        setDog(newDog); // <- This doesn't work
    })

}, [])

I can console.log the object, however setDog(newDog) doesn't work. How do I put the data in state?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
kayak
  • 440
  • 3
  • 7
  • 19
  • 1
    why do you think that it does not work? Btw, you're initializing that state, not with a dog, but with an array of dogs, containing a single entry. And where does `id` come from? – Thomas Oct 14 '20 at 02:10
  • Because when I console lodded `dog` after `setDog(newDog);` the value was empty. – kayak Oct 14 '20 at 02:25
  • id is from dogs list page. I was using useParams() to get an id. – kayak Oct 14 '20 at 02:26
  • *"when I console lodded `dog` after `setDog(newDog);` the value was empty."* `setDog` is async and `dog` is a constant. On the next render, the constant will contain the new value. – Thomas Oct 14 '20 at 02:29

0 Answers0