Last active
January 19, 2021 11:37
-
-
Save shalahuddinn/5155c51ae43b2000da5a261f0f41cf0c to your computer and use it in GitHub Desktop.
Modify the kuzzle example code to use React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState, useEffect}from 'react'; | |
import kuzzle from './services/kuzzle'; | |
import './App.css'; | |
const Message = ({ message, username }) => { | |
return ( | |
<div className={(message.username === username ? 'fromMe' : 'fromOthers') + ' messages'}> | |
<span> User: <b>{message.username}</b> (</span> | |
<span> {new Date(message.createdAt).toLocaleString().split("GMT")[0]} )</span> | |
<p> {message.value} </p> | |
</div> | |
); | |
} | |
function App() { | |
// const [state, setState] = useState({ | |
// username: "", | |
// message: "", | |
// messages: [], | |
// validate: false, | |
// }); | |
const [username, setUsername] = useState(''); | |
const [message, setMessage] = useState(''); | |
const [messages, setMessages] = useState([]); | |
const [validate, setValidate] = useState(false); | |
// const [messagesFetched, setMessagesFetched] = useState(false); | |
// const [roomId, setRoomId] = useState(null); | |
const valid = async () => { | |
await kuzzle.connect(); | |
if (!await kuzzle.index.exists("chat")) { | |
await kuzzle.index.create("chat"); | |
await kuzzle.collection.create("chat", "messages"); | |
} | |
await subscribeMessages(); | |
await fetchMessages(); | |
// setState({...state, validate: true}); | |
setValidate(true); | |
}; | |
// useEffect | |
const handleInputChange = event => { | |
const { value, name } = event.target; | |
// setState({...state, | |
// [name]: value | |
// }); | |
if (name === 'username') { | |
setUsername(value); | |
} else { | |
setMessage(value); | |
} | |
}; | |
const renderUsernameInput = () => { | |
if (validate === false) { | |
return ( | |
<div className="wrapper"> | |
<input autoFocus name="username" id="username" | |
onKeyUp={handleInputChange} | |
type="text" | |
placeholder="Enter your nickname" | |
/> | |
<button onClick={valid}>Valid</button> | |
</div> | |
); | |
} | |
} | |
const renderMessageInput = () => { | |
if (validate === true) { | |
return ( | |
<div className="wrapper"> | |
<input autoFocus type="text" | |
id="message" | |
name="message" | |
onChange={handleInputChange} | |
placeholder="Enter your message" | |
value={message} | |
/> | |
<button onClick={() => sendMessage()}>Send</button> | |
</div> | |
); | |
} | |
} | |
const getMessage = document => { | |
const message = { | |
_id: document._id, | |
value: document._source.value, | |
createdAt: document._source._kuzzle_info.createdAt, | |
username: document._source.username | |
}; | |
return message; | |
}; | |
const fetchMessages = async () => { | |
const results = await kuzzle.document.search( | |
'chat', | |
'messages', | |
{ | |
sort: { | |
'_kuzzle_info.createdAt': 'desc' | |
} | |
}, | |
{ | |
size: 100 | |
} | |
); | |
let fetchedMessages = results.hits.map(hit => getMessage(hit)); | |
// console.log(messages); | |
// setState({ ...state, messages: messages }) | |
setMessages(fetchedMessages); | |
// setMessagesFetched(true); | |
}; | |
const sendMessage = async () => { | |
if (message === '') return; | |
await kuzzle.document.create( | |
'chat', | |
'messages', | |
{ | |
value: message, | |
username: username | |
} | |
); | |
// console.log("state send message") | |
// console.log(state.validate) | |
// setState({...state, message: '' }) | |
setMessage(''); | |
}; | |
const subscribeMessages = async () => { | |
// return ( | |
const roomId = kuzzle.realtime.subscribe( | |
'chat', | |
'messages', | |
{}, | |
// notificationCallback | |
async (notification) => { | |
if (notification.type !== 'document') return; | |
if (notification.action !== 'create') return; | |
// console.log("state") | |
// console.log(state.validate) | |
setMessages([...messages, getMessage(notification.result)]); | |
// setState({ | |
// messages: [ | |
// ...state.messages, | |
// getMessage(notification.result) | |
// ] | |
// }) | |
} | |
); | |
// setRoomId(roomId); | |
// ) | |
}; | |
return ( | |
<> | |
{renderUsernameInput()} | |
{renderMessageInput()} | |
<div> | |
{messages.map((message, idx) => { | |
return (<Message key={idx} message={message} username={username} />) | |
})} | |
</div> | |
</> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment