Create ideas page_
Add database queries and pagination using Appwrite in your React application.
1 min read
Using the useIdeas hook we can now display the ideas on the page. We will also add a form to submit new ideas.
Overwrite the contents of src/pages/Home.jsx with the following:
JavaScript
import { useState } from "react";import { useUser } from "../lib/context/user";import { useIdeas } from "../lib/context/ideas";
export function Home() { const user = useUser(); const ideas = useIdeas();
const [title, setTitle] = useState(""); const [description, setDescription] = useState("");
const handleSubmit = async () => { try { await ideas.add({ userId: user.current.$id, title, description }); setTitle(""); setDescription(""); } catch (err) { console.error(err); } };
return ( <> {/* Show the submit form to logged in users. */} {user.current ? ( <section> <h2>Submit Idea</h2> <form> <input type="text" placeholder="Title" value={title} onChange={(event) => { setTitle(event.target.value); }} /> <textarea placeholder="Description" value={description} onChange={(event) => { setDescription(event.target.value); }} /> <button type="button" onClick={handleSubmit} > Submit </button> </form> </section> ) : ( <section> <p>Please login to submit an idea.</p> </section> )} <section> <h2>Latest Ideas</h2> <ul> {ideas.current.map((idea) => ( <li key={idea.$id}> <strong>{idea.title}</strong> <p>{idea.description}</p> {/* Show the remove button to idea owner. */} {user.current && user.current.$id === idea.userId && ( <button type="button" onClick={() => ideas.remove(idea.$id)}> Remove </button> )} </li> ))} </ul> </section> </> );}In src/App.jsx, wrap the main element with the IdeasProvider component.
JavaScript
import { Login } from "./pages/Login";import { Home } from "./pages/Home";import { UserProvider } from "./lib/context/user";import { IdeasProvider } from "./lib/context/ideas";
function App() { const isLoginPage = window.location.pathname === "/login";
return ( <div> <UserProvider> <IdeasProvider> <Navbar /> <main>{isLoginPage ? <Login /> : <Home />}</main> </IdeasProvider> </UserProvider> </div> );}
export default App;Was this page helpful?
Share what worked or what we should fix. Once approved, our agents automatically apply suggested updates to the docs.