@readr-media/react-feedback
Version:
## Installation `yarn install`
156 lines (132 loc) • 5.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useComments;
var _react = _interopRequireWildcard(require("react"));
var _uuid = require("uuid");
var _api = require("../api");
var _useUser = _interopRequireDefault(require("./use-user"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const initialCommentCount = 3;
const moreCommentCount = 10;
/**
* @typedef {import('../../typedef').Comment} Comment
* @typedef {import('../../typedef').CommentManager} CommentManager
*
* @param {string} formId
* @param {string} fieldId
* @param {string} [identifier]
* @return {CommentManager}
*/
function useComments(formId, fieldId, identifier) {
const [showingComments, setShowingComments] = (0, _react.useState)([]);
const [noMoreComment, setNoMoreComment] = (0, _react.useState)(false);
const hidingCommentsRef = (0, _react.useRef)([]);
const allCommentsRef = (0, _react.useRef)([]);
const skipRef = (0, _react.useRef)(0);
const takeRef = (0, _react.useRef)(initialCommentCount + 2 * moreCommentCount);
const {
userId
} = (0, _useUser.default)();
const convertDateFromISO8601 = dateString => {
const date = new Date(dateString);
return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${(date.getMinutes() < 10 ? '0' : '') + date.getMinutes()}`;
};
const fetchComments = (0, _react.useCallback)(async (showCommentCount, firstTime = false) => {
try {
console.log('fetchComments');
const result = await (0, _api.getFeedbacks)({
form: formId,
field: fieldId,
identifier: identifier,
take: takeRef.current,
skip: skipRef.current
});
if (result !== null && result !== void 0 && result.data) {
const {
data: {
formResults
},
skip
} = result.data;
skipRef.current = skip;
if (firstTime) {
takeRef.current = 2 * moreCommentCount;
}
if (formResults.length) {
const allCommentsIds = allCommentsRef.current.map(comment => comment.id);
const comments = formResults.filter(({
id
}) => allCommentsIds.includes(id) === false).map(({
id,
name,
result,
responseTime
}) => ({
id,
name,
content: result,
date: convertDateFromISO8601(responseTime)
}));
if (comments.length !== formResults.length) {
console.log('filter repitition');
}
if (comments.length === 0) {
// handle duplicated request during initialization
return;
}
hidingCommentsRef.current = [...hidingCommentsRef.current, ...comments];
allCommentsRef.current = [...allCommentsRef.current, ...comments];
} else {
setNoMoreComment(true);
}
const commentsToShow = hidingCommentsRef.current.splice(0, showCommentCount);
setShowingComments(comments => [...comments, ...commentsToShow]);
}
} catch (error) {// do nothing for now
}
});
const loadMoreComments = async () => {
if (hidingCommentsRef.current.length < moreCommentCount && !noMoreComment) {
fetchComments(moreCommentCount);
} else {
const commentsToShow = hidingCommentsRef.current.splice(0, moreCommentCount);
setShowingComments(comments => [...comments, ...commentsToShow]);
}
};
const postComment = async textareaValue => {
const date = new Date(); // add comment before sending request
const newComment = {
id: (0, _uuid.v4)(),
//since no return the real id, randomly generate one
name: userId,
content: textareaValue,
date: convertDateFromISO8601(date)
};
setShowingComments(comments => [newComment, ...comments]); // send request without error handle
try {
const result = await (0, _api.postFeedback)({
// eslint-disable-line
name: userId,
form: formId,
identifier: identifier,
responseTime: date,
field: fieldId,
userFeedback: textareaValue
});
} catch (error) {// do nothing for now
}
};
(0, _react.useEffect)(() => {
fetchComments(initialCommentCount, true);
}, []);
return {
comments: showingComments,
noMoreComment,
loadMoreComments,
postComment
};
}