Snippets Collections
document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault();

  const formData = new FormData(this);

  const jsonObject = {};
  formData.forEach(function(value, key) {
    jsonObject[key] = value;
  });

  fetch('your-php-script.php', {
    method: 'POST',
    body: JSON.stringify(jsonObject),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error('Error:', error);
  });
});
const post = async (url, params) => {
    const response = await fetch(url, {
        method: 'POST',
        body: JSON.stringify(params),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        }
    })

    const data = await response.json()

    return data
}

// Then use it like so with async/await:
(async () => {
    const data = await post('https://jsonplaceholder.typicode.com/posts', {
        title: 'This will be the title',
        body: 'Setting the body property',
        userId: 1
    })

    console.log(data)
})()

// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
    title: 'This will be the title',
    body: 'Setting the body property',
    userId: 1,
}).then(data => console.log(data))
async function postData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `data.json()` call
});
$("#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

Tue Aug 01 2023 12:11:52 GMT+0000 (Coordinated Universal Time)

#fetch #fetch_api #form_submit #formdata #json #json.stringify
star

Thu Jun 15 2023 20:05:47 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/courses/learn-intermediate-javascript/lessons/js-requests-with-fetch-api/exercises/making-an-async-get-request

#async #await #fetch
star

Wed Apr 05 2023 17:11:20 GMT+0000 (Coordinated Universal Time) https://webtips.dev/solutions/send-query-params-in-get-and-post-in-javascript

#javascript #fetch
star

Tue Mar 21 2023 05:26:11 GMT+0000 (Coordinated Universal Time)

#fetch #post
star

Thu Aug 18 2022 14:52:57 GMT+0000 (Coordinated Universal Time)

#shopify #fetch
star

Sat May 07 2022 17:19:09 GMT+0000 (Coordinated Universal Time)

#sanity #nextjs #fetch #doble-fetch
star

Sat May 07 2022 17:11:43 GMT+0000 (Coordinated Universal Time)

#sanity #nextjs #fetch #doble-fetch
star

Sat May 07 2022 02:43:48 GMT+0000 (Coordinated Universal Time)

#sanity #nextjs #fetch #doble-fetch
star

Wed Jan 26 2022 02:27:03 GMT+0000 (Coordinated Universal Time)

#javascript #json #auth #fetch
star

Mon Aug 23 2021 18:14:18 GMT+0000 (Coordinated Universal Time)

#fetch #promise
star

Mon May 24 2021 17:37:55 GMT+0000 (Coordinated Universal Time)

#react #api #fetch #async #error
star

Wed May 05 2021 09:20:33 GMT+0000 (Coordinated Universal Time) 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