Estoy tratando de representar un componente de esqueleto al cargar los datos o el componente de error 404 si no se encuentran datos hasta ahora. He intentado usar declaraciones if else y operadores lógicos hasta ahora ninguno funciona correctamente.
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 /> )); }Nota: Los datos se obtienen de dos apis diferentes
Defina una variable de estado de carga de la siguiente manera:
const [isLoading, setIsLoading] = useState(false);Entonces su función fetchPosts sería como:
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); }) };Usando esta variable de carga, puede diferenciar entre las estatuas, por lo que con su jsx puede hacer:
{ loading && <SkeletonItemPage /> } { !loading && posts.length === 0 && <NotFound message='not found' /> }