When article was loaded once than it will be cached in redux store. On the next loading of article content it will be get from store
61 lines
1.7 KiB
TypeScript
Executable File
61 lines
1.7 KiB
TypeScript
Executable File
import React, { useCallback, useState } from "react";
|
|
import { useDispatch } from "react-redux";
|
|
import { ArticleStore } from "../domain/articleStore";
|
|
import type { Article } from "../domain/articleEntity";
|
|
|
|
const useArticleCommonStore = (): ArticleStore => {
|
|
const [isLoading, setLoading] = useState<boolean>(false);
|
|
const [hasError, setError] = useState<boolean>(false);
|
|
const [currentArticle, setCurrentArticle] = useState<Article | null>(null);
|
|
const [articles, setArticlesState] = useState<Array<Article>>([]);
|
|
|
|
const dispatch = useDispatch();
|
|
|
|
const getArticle = useCallback(
|
|
(id: string) => {
|
|
setLoading(true);
|
|
if (typeof currentArticle === undefined) {
|
|
const fromStore = findArticleFromStore(id);
|
|
if (typeof fromStore === undefined) {
|
|
setError(true);
|
|
return null;
|
|
}
|
|
setLoading(false);
|
|
setCurrentArticle(fromStore);
|
|
return fromStore;
|
|
}
|
|
setLoading(false);
|
|
return currentArticle;
|
|
},
|
|
[dispatch]
|
|
);
|
|
|
|
const findArticleFromStore = (id: string): Article | null => {
|
|
const filteredArray = articles.filter((e) => e.id == id);
|
|
if (filteredArray.length > 0) {
|
|
return filteredArray[0];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const setNewArticle = (newArticle: Article) => {
|
|
setCurrentArticle(newArticle);
|
|
if (!articles.includes(newArticle)) {
|
|
setArticlesState(articles.concat([newArticle]));
|
|
} else if (articles.length == 0) {
|
|
setArticlesState([newArticle]);
|
|
}
|
|
}
|
|
|
|
return {
|
|
articles: articles,
|
|
currentArticle: currentArticle,
|
|
isLoading,
|
|
hasError,
|
|
setArticle: setNewArticle,
|
|
getArticle: getArticle,
|
|
};
|
|
};
|
|
|
|
export { useArticleCommonStore };
|