6 - Context State
6.1 Using Context API

Using Context API

Before we add and more functionality to our app, let's lift up our state so we can have eaiser access to our note's and any other relevant state. We'll do this by using the context API, and by setting a note context.

Create context

Lets create our note context in its own folder/file: src/context/NoteContext.jsx

NoteContext.jsx
import { createContext } from "react";
import { useState, useEffect } from "react";
import Spinner from "../icons/Spinner";
import { db } from "../appwrite/databases";
 
export const NoteContext = createContext();
 
const NotesProvider = ({ children }) => {
    const [loading, setLoading] = useState(true);
    const [notes, setNotes] = useState();
 
    useEffect(() => {
        init();
    }, []);
 
    const init = async () => {
        const response = await db.notes.list();
        setNotes(response.documents);
        setLoading(false);
    };
 
    const contextData = { notes, setNotes };
 
    return (
        <NoteContext.Provider value={contextData}>
            {loading ? (
                <div
                    style={{
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        height: "100vh",
                    }}
                >
                    <Spinner size="100" />
                </div>
            ) : (
                children
            )}
        </NoteContext.Provider>
    );
};
export default NotesProvider;

Add Context Provider

To make our state inside of NoteContext availble throughout our app lets wrap our NotesPage with our NotesProvider

App.jsx
import NoteProvider from "./context/NoteContext";
 
function App() {
    return (
        <div id="app">
            <NoteProvider>
                <NotesPage />
            </NoteProvider>
        </div>
    );
}

Now within our NotesPage we can update our code to use the notes state from our context.

You can now remove any code that I have commented out.

NotesPage.jsx
import { useContext } from "react";
import { NoteContext } from "../context/NoteContext";
 
const NotesPage = () => {
    const { notes, setNotes } = useContext(NoteContext);
 
    // const [notes, setNotes] = useState([]);
 
    // useEffect(() => {
    //     init();
    // }, []);
 
    // const init = async () => {
    //     const response = await db.notes.list();
    //     setNotes(response.documents);
    // };
    //...

Delete DeleteButton

Now that we are getting our notes data from our NotesContext, we can remove the setNotes props that were passed into our <NoteCard/> and <DeleteButton/>

Instead, we will access setNotes from our context now

const DeleteButton = ({ noteId }) => {
    const { setNotes } = useContext(NoteContext);