inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

풀스택 리액트 라이브코딩 - 간단한 쇼핑몰 만들기

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

해결된 질문

253

이예은

작성한 질문수 1

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;

 

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

react firebase graphql

답변 1

2

이예은

graphql/cart.ts 파일에서

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

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

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

[useRoutes, React-Query 오류 해결방법] No QueryClient set, use QueryClientProvider to set one 에러 나시는 분 보세요 !!!

4

1210

2

깃허브에서 선생님께서 올리신 파일 받아,, 실행시켜보려했으나 안됩니다

0

343

1

상품목록페이지만들기에서 ... 막힙니다..

0

407

1

강의 시점과 지금시점이 꽤 달라진게 있는거 같아요

0

500

1

상품목록 불러오기, 장바구니 삭제 에러 질문 드립니다

0

411

1

graphqlFetcher 관련 에러와 , data 객체 정의 되지 않는 오류 질문 드립니다

0

572

2

productdetail 데이터 안불러와지고 있습니다.

1

445

1

query 에러 발생했습니다.

1

538

1

react typescript vite 설치시 오류 질문드립니다.

0

1794

2

섹션1의 1강 routes.tsx에서 에러가 발생합니다

0

813

2

routes.tsx에서 질문이 있습니다!

1

576

1

vite-plugin-next-react-router

0

1475

3

grahpqlFetcher 설명가능할까요

1

501

1

msw mocking enabled

1

789

2

[기술 질문아님]

0

551

2

products 라우팅은 되는데 cart 라우팅은 안되네요 ㅠ

0

584

2

caught Error: No QueryClient set, use ueryClientProvider 에러

13

1970

3

Heroku build관련 오류가 발생해 글 남깁니다 ㅠㅠ

0

705

1

firebase filterling 관련 질문

0

568

3

body가 json 형태가 아닌 ReadableStream 형태로 찍힙니다.

0

785

1

graphqlFetcher 관련 에러가 해결이 안됩니다. ㅠㅠ

1

673

3

MSW graphqlFetcher 에러 관련

0

477

1

graphql-tag, graphql-request 패키지를 사용하는 이유가 궁금합니다.

0

790

1

1일차 fetch api 진행 시 CORS 에러

0

1046

2