Snippets Collections
$("#purchase").click(function(){
  var addData = {
    'id':, /* ID Variant */
    'quantity':1
  };

  fetch('/cart/add.js', {
    body: JSON.stringify(addData),
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
      'X-Requested-With':'xmlhttprequest',
    },
    method: 'POST'
  }).then(function(response) {
    return response.json();
  }).then(function(json) {
    /* we have JSON */
    console.log(json)
  }).catch(function(err) {
    /* uh oh, we have error. */
    console.error(err)
  });
  
});
import client, { previewClient } from "./sanity";

const getUniquePosts = (posts) => {
  const slugs = new Set();
  return posts.filter((post) => {
    if (slugs.has(post.slug)) {
      return false;
    } else {
      slugs.add(post.slug);
      return true;
    }
  });
};

const postFields = `
  _id,
  name,
  title,
  'date': publishedAt,
  excerpt,
  'slug': slug.current,
  'coverImage': mainImage.asset->url,
  'author': author->{name, 'picture': image.asset->url},
`;

const getClient = (preview) => (preview ? previewClient : client);

export async function getPreviewPostBySlug(slug) {
  const data = await getClient(true).fetch(
    `*[_type == "post" && slug.current == $slug] | order(dpublishedAtate desc){
      ${postFields}
      body
    }`,
    { slug }
  );
  return data[0];
}

export async function getAllPostsWithSlug() {
  const data = await client.fetch(`*[_type == "post"]{ 'slug': slug.current }`);
  return data;
}

export async function getAllPostsForHome(preview) {
  const results = await getClient(preview)
    .fetch(`*[_type == "post"] | order(date desc, _updatedAt desc){
      ${postFields}
    }`);
  return getUniquePosts(results);
}

/* Relación Post-Author */
export async function getPostAndAuthors() {
  const data = await client.fetch(
    `*[_type == "post"]{title, publishedAt,'author': *[_type == "author" && _id == ^.author._ref && genre== 'comedia']{genre,name, 'picture': image.asset->url} }`
  );

  return data;
}

export async function getPostAndMorePosts(slug, preview) {
  const curClient = getClient(preview);
  const [post, morePosts] = await Promise.all([
    curClient
      .fetch(
        `*[_type == "post" && slug.current == $slug] | order(_updatedAt desc) {
        ${postFields}
        body,
        'comments': *[_type == "comment" && post._ref == ^._id]{name, text, _createdAt}
      }`,
        { slug }
      )
      .then((res) => res?.[0]),
    curClient.fetch(
      `*[_type == "post" && slug.current != $slug] | order(publishedAt desc, _updatedAt desc){
        ${postFields}
        body,
      }[0...2]`,
      { slug }
    ),
  ]);
  return { post, morePosts: getUniquePosts(morePosts) };
}
import styles from "../styles/Home.module.css";
//import imageUrlBuilder from "@sanity/image-url";
import { useState, useEffect } from "react";
import { getPostAndAuthors } from "../lib/api";

export default function Home({ posts }) {
  const [mappedPosts, setMappedPosts] = useState([]);
  console.log("mappedPosts2: ", mappedPosts);
  /*  console.log(
    "mappedPosts: ",
    mappedPosts.map((p, index) => console.log(p[index]))
  );
 */
  useEffect(() => {
    if (posts.length) {
      setMappedPosts(
        posts.map((p) => {
          return {
            ...p,
          };
        })
      );
    } else {
      setMappedPosts([]);
    }
  }, [posts]);

  return (
    <div>
      <div>
        <h3>Recent Posts:</h3>
        {/* Sin  _id == ^.author._ref no te va a hacer la relaciòn */}
        {/* 
          `*[_type == "post"]{
            title, 
            publishedAt,
            'author': *[_type == "author" && _id == ^.author._ref && genre== 'comedia']{
              genre,name, 'picture': image.asset->url} 
            }` 
        */}
        {/* Out:
        [
  {
    "author": [
      {
        "genre": "comedia",
        "name": "Cezar",
        "picture": "https://cdn.sanity.io/images/9w4ss8xn/production/48ef72edee2dd89a71e272beea5721e40281d5a0-340x317.jpg"
      }
    ],
    "publishedAt": "2022-05-05T02:37:00.000Z",
    "title": "Cuentos"
  },
  {
    "author": [
      {
        "genre": "comedia",
        "name": "Cezar",
        "picture": "https://cdn.sanity.io/images/9w4ss8xn/production/48ef72edee2dd89a71e272beea5721e40281d5a0-340x317.jpg"
      }
    ],
    "publishedAt": "2022-05-06T02:36:00.000Z",
    "title": "Tormenta"
  },
  {
    "author": [],
    "publishedAt": "2022-05-04T02:38:00.000Z",
    "title": "Rios del Desierto"
  }
]
           
        */}
        <div>
          {mappedPosts.map((p, index) => (
            <div className={styles.post} key={index}>
              <h4>{p.author.length > 0 ? p.title : null}</h4>
              {p.author.map((a, index) => (
                <p key={index}>{a.name}</p>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export const getServerSideProps = async () => {
  const posts = await getPostAndAuthors();
  return {
    props: {
      posts,
    },
  };
};

/* export async function getStaticPaths() {
  const allPosts = await getAllPostsWithSlug();
  return {
    paths:
      allPosts?.map((post) => ({
        params: {
          slug: post.slug,
        },
      })) || [],
    fallback: true,
  };
} */
import Head from "next/head";
import styles from "../styles/Home.module.css";
import { Toolbar } from "../components/toolbar";
import imageUrlBuilder from "@sanity/image-url";
import { useState, useEffect } from "react";
import { useRouter } from "next/router";

export default function Home({ posts, authors }) {
  const router = useRouter();
  const [mappedPosts, setMappedPosts] = useState([]);
  const [mappedAuthors, setMappedAuthors] = useState([]);
  console.log(mappedAuthors);
  console.log("mappedPosts: ", mappedPosts);

  useEffect(() => {
    if (posts.length && authors.length) {
      const imgBuilder = imageUrlBuilder({
        projectId: "9w4ss8xn",
        dataset: "production",
      });

      setMappedPosts(
        posts.map((p) => {
          return {
            ...p,
            mainImage: imgBuilder.image(p.mainImage).width(500).height(250),
          };
        })
      );
      setMappedAuthors(
        authors.map((a) => {
          return {
            ...a,
            image: imgBuilder.image(a.image).width(100).height(100),
          };
        })
      );
    } else {
      setMappedPosts([]);
    }
  }, [posts, authors]);

  return (
    <div>
      <Toolbar />
      <div className={styles.main}>
        <h1>Welcome To My Blog</h1>

        <h3>Recent Posts:</h3>

        <div className={styles.feed}>
          {mappedPosts.length ? (
            mappedPosts.map((p, index) => (
              <div key={index} className={styles.post}>
                <div
                  onClick={() => router.push(`/post/${p.slug.current}`)}
                  key={index}
                  className={styles.post}
                >
                  <h3>{p.title}</h3>
                  <img className={styles.mainImage} src={p.mainImage} />
                </div>
                {mappedAuthors
                  .filter((a) => a._id === p.author._ref)
                  .map((a, index) => (
                    <div key={index}>
                      <img src={a.image} />
                      <h4>{a.name}</h4>
                    </div>
                  ))}
              </div>
            ))
          ) : (
            <>No Posts Yet</>
          )}
        </div>
      </div>
    </div>
  );
}

export const getServerSideProps = async (pageContext) => {
  const query = encodeURIComponent('*[ _type == "post" ]');
  const qauthors = encodeURIComponent('*[ _type == "author" ]');
  const url = `https://9w4ss8xn.api.sanity.io/v1/data/query/production?query=${query}`;
  const urlauthors = `https://9w4ss8xn.api.sanity.io/v1/data/query/production?query=${qauthors}`;
  const result = await fetch(url).then((res) => res.json());
  const resultauthors = await fetch(urlauthors).then((res) => res.json());

  if (
    !result.result ||
    !result.result.length ||
    !resultauthors.result ||
    !resultauthors.result.length
  ) {
    return {
      props: {
        posts: [],
        authors: [],
      },
    };
  } else {
    return {
      props: {
        posts: result.result,
        authors: resultauthors.result,
      },
    };
  }
};
const token = 'YOUR_TOKEN_HERE';
fetch('https://api.github.com/user/repos', {
  headers: {
    Authorization: `token ${token}`
  }
})
  .then(res => res.json())
  .then(json => console.log(json));
fetch("https://free-nba.p.rapidapi.com/teams?page=0", {
	"method": "GET",
	"headers": {
		"x-rapidapi-host": "free-nba.p.rapidapi.com",
		"x-rapidapi-key": "d1e022a733msh4e2c4a1ea244bf9p1a3971jsnea127bfc9297"
	}
})
.then((response) => {
  return response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
  console.log(responseData.data);
 
})
.catch(err => {
	console.error(err);
});
  const getMovies = async (url) => {
    setError(null);
    try {
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error("Something went wrong!");
      }

      const data = await response.json();
      
      if (data.results.length === 0) {
        throw new Error("Sorry, no movies were found.");
      }
      
      const transformedMovies = data.results.map((movie) => {
        return {
          id: movie.id,
          title: movie.title,
          description: movie.overview,
          rating: movie.vote_average,
          genres: movie.genre_ids,
          poster_path: movie.poster_path,
          backdrop_path: movie.backdrop_path,
          year: movie.release_date
        }
      })
      setTotalPages(data.total_pages);
      setMovies(transformedMovies);
      chooseMovie(transformedMovies);
    } catch (errorThrown) {
      setError(errorThrown.message);
    }
  }
fetch("http://www.omdbapi.com/?s=harry potter&apikey=adf1f2d7")
  .then(response => response.json())
  .then((data) => {
    console.log(data);
  });
star

Thu Aug 18 2022 14:52:57 GMT+0000 (UTC)

#shopify #fetch
star

Sat May 07 2022 17:19:09 GMT+0000 (UTC)

#sanity #nextjs #fetch #doble-fetch
star

Sat May 07 2022 02:43:48 GMT+0000 (UTC)

#sanity #nextjs #fetch #doble-fetch
star

Wed Jan 26 2022 02:27:03 GMT+0000 (UTC)

#javascript #json #auth #fetch
star

Mon Aug 23 2021 18:14:18 GMT+0000 (UTC)

#fetch #promise
star

Wed May 05 2021 09:20:33 GMT+0000 (UTC) https://kitt.lewagon.com/camps/591/lectures/04-Front-End/06-HTTP-and-AJAX

#fetch #json #get

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension