firebase数据库订单按日期订购

发布于 2025-02-12 14:27:54 字数 3138 浏览 0 评论 0 原文

我正在使用 React firebase 实时数据库制作待办事项列表应用程序。

我想在日期下订购的戒酒。

我的数据库:

> ,有没有办法从客户端订购它(React)?

我的代码

todos.js:

import { useState, useEffect } from "react";
import { signOut, onAuthStateChanged } from "firebase/auth";
import { uid } from "uid";
import { set, ref, onValue } from "firebase/database";
import { auth, db } from "../firebase";
import moment from "moment";

function Todos() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        onValue(ref(db, `/${auth.currentUser.uid}`), (snapshot) => {
          setTodos([]);
          const data = snapshot.val();
          if (data !== null) {
            Object.values(data).map((todo) => {
              setTodos((currentTodos) => [todo, ...currentTodos]);
            });
          }
        });
      } else {
        navigate("/");
      }
    });
  }, []);

  const handleSignOut = () => {
    signOut(auth)
      .then(() => navigate("/"))
      .catch((error) => alert(error.message));
  };

  const addTodo = () => {
    const uidd = uid();
    set(ref(db, `${auth.currentUser.uid}/${uidd}`), {
      task: newTodo,
      uid: uidd,
      createdAt: moment().format("YYYY-MM-DD k:m:s"),
    });

    setNewTodo("");
  };

  return (
    <>
      <Center>
        <Button colorScheme="red" marginTop={5} onClick={handleSignOut}>
          Logout
        </Button>
      </Center>
      <Container
        maxW="4xl"
        marginTop={8}
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <Box
          boxShadow="base"
          rounded="lg"
          padding={10}
          background="white"
          width="100%"
        >
          <Heading as="h1" size="md" textAlign="center">
            Todo List App
          </Heading>
          <form onSubmit={(e) => e.preventDefault()}>
            <Box
              display="flex"
              alignItems="center"
              justifyContent="space-between"
              marginTop={5}
            >
              <Input
                placeholder="New Task"
                value={newTodo}
                onChange={(e) => setNewTodo(e.target.value)}
                size="lg"
                width="80%"
              />
              <Button
                colorScheme="teal"
                height={45}
                rightIcon={<MdAdd />}
                margin={0}
                onClick={addTodo}
                type="submit"
              >
                Add
              </Button>
            </Box>
          </form>
          {todos.map((todo, index) => {
            return <Todo key={index} task={todo.task} uid={todo.uid} />;
          })}
        </Box>
      </Container>
    </>
  );
}

export default Todos;

I'm making a todo list app using react and firebase realtime database.

I want to get the todos ordered by date.

My Database: photo

And if I cant do this from firebase, is there a way to order it from the client side (react)?

My Code

Todos.js:

import { useState, useEffect } from "react";
import { signOut, onAuthStateChanged } from "firebase/auth";
import { uid } from "uid";
import { set, ref, onValue } from "firebase/database";
import { auth, db } from "../firebase";
import moment from "moment";

function Todos() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        onValue(ref(db, `/${auth.currentUser.uid}`), (snapshot) => {
          setTodos([]);
          const data = snapshot.val();
          if (data !== null) {
            Object.values(data).map((todo) => {
              setTodos((currentTodos) => [todo, ...currentTodos]);
            });
          }
        });
      } else {
        navigate("/");
      }
    });
  }, []);

  const handleSignOut = () => {
    signOut(auth)
      .then(() => navigate("/"))
      .catch((error) => alert(error.message));
  };

  const addTodo = () => {
    const uidd = uid();
    set(ref(db, `${auth.currentUser.uid}/${uidd}`), {
      task: newTodo,
      uid: uidd,
      createdAt: moment().format("YYYY-MM-DD k:m:s"),
    });

    setNewTodo("");
  };

  return (
    <>
      <Center>
        <Button colorScheme="red" marginTop={5} onClick={handleSignOut}>
          Logout
        </Button>
      </Center>
      <Container
        maxW="4xl"
        marginTop={8}
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <Box
          boxShadow="base"
          rounded="lg"
          padding={10}
          background="white"
          width="100%"
        >
          <Heading as="h1" size="md" textAlign="center">
            Todo List App
          </Heading>
          <form onSubmit={(e) => e.preventDefault()}>
            <Box
              display="flex"
              alignItems="center"
              justifyContent="space-between"
              marginTop={5}
            >
              <Input
                placeholder="New Task"
                value={newTodo}
                onChange={(e) => setNewTodo(e.target.value)}
                size="lg"
                width="80%"
              />
              <Button
                colorScheme="teal"
                height={45}
                rightIcon={<MdAdd />}
                margin={0}
                onClick={addTodo}
                type="submit"
              >
                Add
              </Button>
            </Box>
          </form>
          {todos.map((todo, index) => {
            return <Todo key={index} task={todo.task} uid={todo.uid} />;
          })}
        </Box>
      </Container>
    </>
  );
}

export default Todos;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

御守 2025-02-19 14:27:54

由于您正在为单个用户加载Todos,因此您 can 的确是通过其 Create 属性订购的。为此,请使用

const ref = ref(db, `/${auth.currentUser.uid}`);
const query = query(ref, orderByChild('createdAt'));
onValue(query, (snapshot) => {
  ...

在代码中,您需要确保使用 snapshot.foreach 按顺序循环循环循环 .val()之前将返回JSON对象,而JSON对象中的属性则是定义上的:

snapshot.forEach((child) => {
  console.log(child.key, child.val());
});

Since you are loading the TODOs for a single user, you can indeed order them by their createdAt property. To do this, use a query as shown in the documentation on ordering and filtering data:

const ref = ref(db, `/${auth.currentUser.uid}`);
const query = query(ref, orderByChild('createdAt'));
onValue(query, (snapshot) => {
  ...

Inside the code you'll then need to make sure to use snapshot.forEach to loop over the children in order, as calling .val() before that will return a JSON object and the properties in a JSON object are by definition not ordered:

snapshot.forEach((child) => {
  console.log(child.key, child.val());
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文