Swalt
Swalt

Reputation: 47

Mapping into firestore from React

I am new to react and firebase/firestore.

I am trying to map into what I believe to be a nested firestore value. I am able to pull each value individually

function Pull() {

    const [blogs,setBlogs]=useState([])
  
    const fetchBlogs=async()=>{  
      const response=firestore.collection('customer');
  
      const data= await response.get();
  
      data.docs.forEach(item=>{
      setBlogs(data.docs.map(d => d.data()))
      console.log(data)
      })
    }
        
    useEffect(() => {
  
      fetchBlogs();
  
    }, [])
    return (
      <div className="App">
        {
            blogs.map((items)=>(
                <div>
                    <p>{items[1].name}</p>
                    
                </div>
            ))
        }
      </div>
    );
  }

I have been trying to map twice to get into the string inside the collection, yet I have had no luck.

My FireStore collection

https://drive.google.com/file/d/1Erfi2CVrBSbWocQXGR5PB_ozgg9KEu12/view?usp=sharing

Thank you for your time!

Upvotes: 2

Views: 132

Answers (2)

Drew Reese
Drew Reese

Reputation: 202721

If you are iterating a data.docs array and enqueueing multiple state updates then you will want to use a functional state update to correctly enqueue, and update from the previous state.

const fetchBlogs = async ( )=> {
  const response = firestore.collection('customer');
  const data = await response.get();

  data.docs.forEach(item => {
    setBlogs(blogs => blogs.concat(item.data()))
  });
}

or you can map the data.docs to an array of items and update state once.

const fetchBlogs = async ( )=> {
  const response = firestore.collection('customer');
  const data = await response.get();

  setBlogs(blogs => blogs.concat(data.docs.map(item => item.data())));
}

Upvotes: 3

Jack Micco
Jack Micco

Reputation: 1

try changing the foreach to a snapshot like this:

data.docs.onSnapshot(snapshot=>{
  setBlogs(snapshot.docs.map(d => d.data()))
  console.log(data)
})

ive used it like this in the past multiple times and it has worked. If it doesnt work, the instagram clone tutorial on youtube by Clever Programmer goes over this well.

Upvotes: 0

Related Questions