-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathSearchContext.tsx
More file actions
100 lines (91 loc) · 2.44 KB
/
SearchContext.tsx
File metadata and controls
100 lines (91 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"use client";
import React, { createContext, useState, useEffect, ReactNode } from "react";
interface Snippet {
_id: any;
title: string;
language: string;
code: string;
description?: string;
tags: string[];
category: string;
difficulty: string;
usage: string;
userId: string;
bookmarkedBy: string[];
}
interface SearchContextProps {
searchQuery: string;
setSearchQuery: (query: string) => void;
snippets: Snippet[];
setSnippets: React.Dispatch<React.SetStateAction<Snippet[]>>;
userId: string | null;
setUserId: React.Dispatch<React.SetStateAction<string | null>>;
loading: boolean;
setLoading: React.Dispatch<React.SetStateAction<boolean>>;
}
export const SearchContext = createContext<SearchContextProps>({
searchQuery: "",
setSearchQuery: () => {},
snippets: [],
setSnippets: () => {},
userId: null,
setUserId: () => {},
loading: false,
setLoading: () => {},
});
export const SearchProvider = ({ children }: { children: ReactNode }) => {
const [searchQuery, setSearchQuery] = useState<string>("");
const [snippets, setSnippets] = useState<Snippet[]>([]);
const [userId, setUserId] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
const fetchSnippets = async () => {
setLoading(true);
try {
const response = await fetch("/api/snippets");
if (!response.ok) {
throw new Error("Failed to fetch snippets");
}
const data = await response.json();
setSnippets(data);
} catch (error) {
console.error("Error fetching snippets:", error);
} finally {
setLoading(false);
}
};
const fetchCurrentUser = async () => {
setLoading(true);
try {
const response = await fetch("/api/getCurrentUser");
if (!response.ok) {
throw new Error("Failed to fetch user data");
}
const userData = await response.json();
setUserId(userData.id || null);
} catch (error) {
console.error("Error fetching current user:", error);
} finally {
setLoading(false);
}
};
fetchSnippets();
fetchCurrentUser();
}, []);
return (
<SearchContext.Provider
value={{
searchQuery,
setSearchQuery,
snippets,
setSnippets,
userId,
setUserId,
loading,
setLoading,
}}
>
{children}
</SearchContext.Provider>
);
};