• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

장바구니 담기 버튼 누르면 404에러가 뜹니다

24.01.16 21:42 작성 조회수 91

0

스크린샷 2024-01-16 오후 9.35.11.png강의 여러번 돌려보고 커뮤니티 질문에도 찾아보고 구글링도 해봤는데 어디서 뭐가 잘못된 건지도 모르겠어서 질문 올립니다! 대체 어디서 잘못 된 걸까요,,,

queryClient.ts

import request, { RequestDocument } from "graphql-request";
import {
  useQuery,
  useMutation,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from "react-query";

// any 타입 미리 만들어줌
type AnyOBJ = { [key: string]: any };

// Create a client
export const getClient = (() => {
  let client: QueryClient | null = null;

  return () => {
    if (!client)
      client = new QueryClient({
        defaultOptions: {
          queries: {
            // 캐시타임 : 이 시간 안에는 다시 상세페이지 들어가도 요청 안 함
            cacheTime: 1000 * 60 * 60 * 24,
            staleTime: 1000 * 60,
            refetchOnMount: false,
            refetchOnReconnect: false,
            refetchOnWindowFocus: false,
          },
        },
      });
    return client;
  };
})();

// 기본 url
const BASE_URL = "/";

// restFetcher async로 요청
export const restFetcher = async ({
  method,
  path,
  body,
  params,
}: {
  // 메소드 타입 정의
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

  // url대신 path를 받음
  path: string;

  // post나 put의 경우엔 body가 필요하므로
  body?: AnyOBJ;

  // 파라미터
  params?: AnyOBJ;
}) => {
  try {
    // 기본 url + path
    let url = `${BASE_URL}${path}`;

    // RequestInit은 node에 기본적으로 정의되어 있음
    const fetchOptions: RequestInit = {
      method,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": BASE_URL,
      },
    };

    // param이 오면
    if (params) {
      const searchParams = new URLSearchParams(params);
      url += "?" + searchParams.toString();
    }

    // body가 오면
    if (body) fetchOptions.body = JSON.stringify(body);

    // url와 옵션들 요청
    // 메서드와 path를 받아서 완성
    const res = await fetch(url, fetchOptions);

    // 받은 것을 json으로 바꾸기
    const json = await res.json();
    return json;

    // 에러 출력
  } catch (err) {
    console.error(err);
  }
};

// graphqlFetcher
export const graphqlFetcher = <T>(query: RequestDocument, variables = {}) =>
  request<T>(BASE_URL, query, variables);

// 쿼리 키 만들기
export const QueryKeys = {
  PRODUCTS: "PRODUCTS",
  CART: "CART",
};

 

product/item.tsx 컴포넌트

import { Link } from "react-router-dom";
import { Product } from "../../../graphql/products";
import { useMutation } from "react-query";
import { graphqlFetcher } from "../../../queryClient";
import { ADD_CART, Cart } from "../../../graphql/cart";

const ProductItem = ({ imageUrl, price, title, id }: Product) => {
  const { mutate: addCart } = useMutation(({ id }: { id: string }) =>
    graphqlFetcher(ADD_CART, { id })
  );

  return (
    <li className="products-item">
      <Link to={`/products/${id}`}>
        <p className="products-item__title">{title}</p>
        <img className="products-item__image" src={imageUrl} />
        <span className="products-item__price">${price}</span>
      </Link>
      <button
        className="product-item__add-cart"
        onClick={() => {
          addCart({ id });
        }}
      >
        장바구니 담기
      </button>
    </li>
  );
};

export default ProductItem;

 

콘솔에 뜨는 오류나는 파일 올려드립니다..

답변 1

답변을 작성해보세요.

2

이예은님의 프로필

이예은

질문자

2024.01.17

graphql/cart.ts 파일에서

import { gql } from "graphql-request";
이거를 

import { gql } from "graphql-tag";
이렇게 바꿨더니 해결됐습니다!

혹시나 저같은 오류 만나시는 분 있을까봐 댓글 달아요!