I am trying to render a skeleton component on loading of the data or 404 error component if data not found so far i have tried using if else statements and logical operators so far none work properly.
const [post, setPost] = useState(null);
const [postExternal, setPostExternal] = useState([]);
const fetchPost = () => {
axios.get(`${API_ONE}/posts?id=${id}`).then((response) => {
setPost(response.data);
});
axios.get(`${API_TWO}/posts?id=${id}`).then((response) => {
setPostExternal(response.data);
});
return;
};
const location = useLocation();
const id = location.pathname.split('/')[2];
useEffect(() => {
fetchPost();
}, [id]);
{
post && postExternal && (
<div>
<h1>{post.title}</h1>
<img src={postExternal} />
</div>
);
}
{
!post &&
(post && post.id === postExternal.id ? (
<NotFound message='not found' />
) : (
<SkeletonItemPage />
));
}
Note: The data is fetched from two different apis
Define a loading state variable as the follow:
const [isLoading, setIsLoading] = useState(false);
Then your fetchPosts function would be like:
const fetchPost = () => {
const apiOnePromise = axios.get(`${API_ONE}/posts?id=${id}`);
const apiTwoPromise = axios.get(`${API_TWO}/posts?id=${id}`);
//toggle loader
setLoading(true);
Promise.all([apiOnePromise, apiTwoPromise])
.then(values => {
//handle your responses here
})
.finally(() => {
//toggle loader again
setLoading(false);
})
};
Using this loading variable you can differentiate between the statues, so with your jsx you can do:
{ loading && <SkeletonItemPage /> }
{ !loading && posts.length === 0 && <NotFound message='not found' /> }