generated from algolia-samples/sample-application
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchAlerts.tsx
95 lines (87 loc) · 2.72 KB
/
SearchAlerts.tsx
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
import React, {useState, useCallback} from "react";
import {Button, Modal, Input, stl} from "@algolia/satellite";
import {connectStateResults, CurrentRefinements} from "react-instantsearch-dom";
import {Bell, Mail, Phone} from "react-feather";
import algoliaHelper, {SearchResults} from "algoliasearch-helper";
import db from "./db";
import searchClient from "./searchClient";
// Transform the current search state (query and facets) to a string.
const serializeSearchState = (searchResults: SearchResults): null|string => {
const state = searchResults && searchResults._state;
if (!state) {
return null;
}
const helper = algoliaHelper(searchClient, state.index, state);
const rawQuery = helper.getQuery();
return JSON.stringify(rawQuery);
};
const SearchAlerts = ({searchResults}: {searchResults: SearchResults}) => {
const [modalShown, setModal] = useState(false);
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const toggleModal = useCallback(() => {
setModal((v) => !v);
}, []);
// Save the serialized search state to the Firebase database,
// with the email / phone of the customer.
const saveSearch = () => {
const query = serializeSearchState(searchResults);
db.collection("alerts").doc().set({
email,
phone,
query,
})
.then(() => {
console.log("Query successfully saved!");
})
.catch((error) => {
console.error("Error saving query: ", error);
});
};
return (
<div className={stl`flex flex-col w-full mb-6`}>
<Button
variant="primary"
startIcon={Bell}
onClick={() => toggleModal()}
>
Alert me!
</Button>
<Modal
open={modalShown}
onDismiss={() => toggleModal()}
title="Don't miss anything!"
>
<div className={stl`mb-6`}>
<CurrentRefinements />
</div>
<div className={stl`mb-6`}>
<Input
placeholder="Email"
type="email"
startIcon={Mail}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className={stl`mb-6`}>
<Input
placeholder="Phone"
startIcon={Phone}
onChange={(e) => setPhone(e.target.value)}
/>
</div>
<div className={stl`flex flex-col w-full`}>
<Button
variant="primary"
onClick={() => saveSearch()}
disabled={!email && !phone}
>
Be notified about new results matching your criteria!
</Button>
</div>
</Modal>
</div>
);
};
const ConnectedSearchAlerts = connectStateResults(SearchAlerts);
export default ConnectedSearchAlerts;