Video Tutorial Comment module: React
In this second chapter we will create the interface part of our comments module based on the React library.
Before you begin it is important to think about the reason behind the use of the library. For this comment module there will be a lot of user actions and their actions result in changes at the interface level. To simplify the transformations and manipulation of the DOM we will use React. It will allow us to represent our interface as a function of the state and we will thus be able to concentrate on the change of this state (it is React who will take care of synchronizing the dom and it will thus offer us an additional level of abstraction ). We could use Preact here if we want a lighter alternative and if we don't plan to use React in the rest of our application.
Hooks
For this kind of module we will need to communicate with the API and perform operations that are very generic. Typically we will call a URL, display a spinner while loading, and then display the results. This logic being very generic we will be able to extract it in layers that we can then reuse throughout our project.
function Comments ({post, user}) {
// This hook allows to manage all the recovery part independently of the component
const {items: comments, setItems: setComments, loading, count, hasMore} = usePaginatedFetch ('/ api / comments? post =' + post)
// We manage the mutations specific to our component (but we could abstract it in a function if this logic is repeated)
const addComment = useCallback (comment => {
setComments (comments => (comment, ... comments))
}, ())
const deleteComment = useCallback (comment => {
setComments (comments => comments.filter (c => c! == comment))
}, ())
const updateComment = useCallback ((newComment, oldComment) => {
setComments (comments => comments.map (c => c === oldComment? newComment: c))
}, ())
// We make the component
return
{user && }
{comments.map (c =>
)}
{hasMore && }
}
The goal of hooks is to be able to separate the mutations of the state of the interface part.