Luka Miljković
Luka Miljković

Reputation: 126

How to get a nested Firebase array as a collection?

I want to display only the currently logged-in user's todos. I made it so that when the user logs in, a new doc is made in the 'users' collection. The new user has the same id as the authenticated user's uid. I also implemented a way to push a new todo only into the current user's todos array. Now I just want to display those todos. This is how the data looks: enter image description here

Before this, I already implemented a way to add and display the todos regardless of the current user. This is the code for displaying the todos:

const todosRef = collection(db, 'todos');
const [newTodos, setNewTodos] = useState([]);

    //get the db data
    useEffect(() => {
        const getTodos = async () => {
            const q = query(todosRef, orderBy("importance", "desc"));
            const data = await getDocs(q);
            setNewTodos(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
        }
        getTodos();
    }, [])

I just need to modify the todosRef probably, but I don't know how.

Upvotes: 0

Views: 58

Answers (1)

Luka Miljković
Luka Miljković

Reputation: 126

I got it to work. Kind of.

const [user, setUser] = useState({});
const [newTodos, setNewTodos] = useState([]);

useEffect(() => {
        onAuthStateChanged(auth, (currentUser) => {
            setUser(currentUser);
        });

    }, [])

useEffect(() => {
        const getTodos = async () => {
            const todoDoc = doc(db, "users", user.uid);
            const docSnap = await getDoc(todoDoc);
            const arrayTodos = docSnap.data().todos;
            setNewTodos(arrayTodos);
        }
        getTodos();
    }, [])

The code will display the todos from the current user, but when I refresh the page, the todos are not displayed. They are still in the db, but are not displayed. Why is that?

Added Note

When I edit the code and save it the todos show. But when I refresh the page, they are gone.

Solved kind of

I think I know why I get this behaviour. When I log in, I set a new user every time into my 'users' collection. I set the users name only as a property. And every time I try to log in, all the todos are deleted, because of that.

const navigate = useNavigate();

    const addUser = async (username, userid) => {
        await setDoc(doc(db, 'users', userid), {
            name: username
        })
    }

    const signInWithGoogle = async () => {
        signInWithPopup(auth, provider).then(result => {
            const username = result.user.displayName;
            const userId = result.user.uid;
            navigate('/todos');
            addUser(username, userId);
        }).catch(err => {
            console.log(err);
        })
    }

Upvotes: 2

Related Questions