#error

질문 11
해시태그 없이 키워드만 일치하는 질문은 개수에 포함되지 않아요.

2달 전 · 이병욱 님의 질문

[express] new Error() 관련 문의

안녕하세요. express 로 개발하고 있는 사람입니다. 저희 프로젝트의 구조는 new Error() 를 전달 해서 상위에서 try/catch로 해당 에러를 잡아서 로깅을 해주고 있습니다. 여기서 로깅을 할 때 파일명과 라인을 받기 위한 Error().stack을 사용해서 보고 있는데 가장 처음 error가 발생한 곳이 아니라 try/catch 하는 곳에 있는 stack 이 나오고 있습니다. 이 상황을 어떻게 하는게 좋을지 알려주실 수 있을까요? 기본적으로 이런 상황에서 로깅은 어떻게 할 수 있을지도 문의드립니다. 감사합니다.

개발자

#express

#log

답변 0

댓글 0

조회 57

4달 전 · 이다솜 님의 질문

cpp 에서 enum class 복사가 가능한가요 ?

안녕하세요 ! 질문 제목이 좀 명확하지 않아서 죄송합니다 ㅠㅠ 다름이 아니라 새로운 enum class 를 구현할 때 이미 구현된 타 enum class를 그대로 가져올 수 있는지 궁금합니다 ! 예를 들어 아래 코드와 같이 (당연히 error 발생하는 코드인 것은 알고 있지만.. 제가 궁금한 부분을 설명 드리기 위해...) enum class ONE { AA, BB }; enum class TWO = ONE; // error.. TWO 라는 enum class 를 새로 구현할 때 이미 구현된 ONE enum class 를 그대로 복사해오도록 구현하는 방법이 궁금합니다 ! 그냥 ONE enum class 사용하면 될 것이지 굳이 새로운 TWO enum class를 생성할 필요가 있나 ~ 라고 당연히 생각하시겠지만... 현재 저의 상황을 설명드리긴 좀 기네요 ㅠㅠ Qt/qml 구조도 설명드려야 되고... 몇시간 째 구글링을 해봐도 답을 못찾겠네요 ㅠㅠ 답변 주시면 무척 감사하겠습니다 !

개발자

#c++

#enum

#질문

답변 0

댓글 0

조회 40

7달 전 · 문종호 님의 새로운 답변

RAG 를 짜는 중에 도무지 어떤 부분이 문제인지 모르겠습니다.

# JSON 파일에서 FAQ 데이터를 로드하는 함수 def load_faq_data_from_json(file_path): with open(file_path, 'r', encoding='utf-8') as f: faq_data = json.load(f) return faq_data # FAQ 데이터 로드 json_file_path = '' faq_data = load_faq_data_from_json(json_file_path) # ChromaDB 클라이언트 및 Embedding 설정 chroma_client = chromadb.Client() # ChromaDB 클라이언트 생성 # 고유한 컬렉션 이름 생성 collection_name = "faq_data_" + datetime.datetime.now().strftime("%Y%m%d_%H%M%S") collection = chroma_client.create_collection(collection_name) # LangChain의 Text Splitter 설정 text_splitter = RecursiveCharacterTextSplitter( chunk_size=512, chunk_overlap=50 ) # OpenAI 임베딩 설정 openai_api_key = '' embedding_function = OpenAIEmbeddings( model="text-embedding-ada-002", openai_api_key=openai_api_key ) # 텍스트 스플리팅 및 임베딩 생성 함수 def split_and_embed_text(text): splitted_texts = text_splitter.split_text(text) print(f"Splitted texts: {splitted_texts}") try: # OpenAIEmbeddings는 embed_documents를 사용합니다. embeddings = embedding_function.embed_documents(splitted_texts) except Exception as e: print(f"임베딩 생성 중 오류 발생: {e}") return None # 임베딩이 제대로 생성되었는지 확인합니다. if embeddings is None or len(embeddings) == 0: print("임베딩 생성 실패") return None # 임베딩을 numpy 배열로 변환 embeddings = np.array(embeddings) print(f"Embeddings shape: {embeddings.shape}") # 임베딩 벡터의 차원을 확인하고 처리합니다. if embeddings.ndim == 1 and embeddings.shape[0] == 1536: # 임베딩이 1차원 배열이고 길이가 1536인 경우 final_embedding = embeddings elif embeddings.ndim == 2 and embeddings.shape[1] == 1536: # 임베딩이 2차원 배열이고 두 번째 차원이 1536인 경우 final_embedding = np.mean(embeddings, axis=0) else: print("임베딩 벡터의 차원이 예상과 다릅니다.") return None print(f"Final embedding shape: {final_embedding.shape}") return final_embedding # FAQ 데이터를 Vector DB에 저장 def store_faq_data_in_vector_db(faq_data, collection): for faq in faq_data: # 'question'과 'answer'가 있는지 확인하고, 'answer'가 None이 아닌지 확인 if 'question' not in faq or 'answer' not in faq or faq['answer'] is None: print(f"누락된 'question' 또는 'answer'로 인해 항목을 건너뜁니다: {faq}") continue # 다음 항목으로 넘어감 # 텍스트 스플리팅 및 임베딩 생성 question_embedding = split_and_embed_text(faq['question']) if question_embedding is None: print(f"Embedding generation failed for question: {faq['question']}") continue # 임베딩이 없으면 다음 질문으로 넘어감 print(f"Generated embedding for question '{faq['question']}': {question_embedding}") # 각 질문에 고유한 ID 생성 faq_id = str(uuid.uuid4()) # 메타데이터에서 None 값을 제거 metadata = {k: v for k, v in {"answer": faq['answer']}.items() if v is not None} # Vector DB에 저장 collection.add( documents=[faq['question']], metadatas=[metadata], ids=[faq_id], embeddings=[question_embedding] ) # 추가 후 임베딩 확인 (저장된 후 곧바로 확인) stored_results = collection.get(ids=[faq_id], include=["embeddings"]) if stored_results['embeddings'] is not None and len(stored_results['embeddings']) > 0: print(f"Embedding for question '{faq['question']}' successfully stored.") else: print(f"Failed to store embedding for question '{faq['question']}'") # FAQ 데이터를 JSON에서 로드하고 저장 store_faq_data_in_vector_db(faq_data, collection) 이렇게 데이터를 저장하고 # 환경 변수에서 API 키 로드 openai_api_key = os.getenv("OPENAI_API_KEY") if not openai_api_key: raise ValueError("OpenAI API 키가 설정되지 않았습니다. 환경 변수 OPENAI_API_KEY를 설정하세요.") # OpenAI 임베딩 설정 embedding_function = OpenAIEmbeddings( model="text-embedding-ada-002", openai_api_key=openai_api_key ) # LangChain의 Text Splitter 설정 (일관성 유지) text_splitter = RecursiveCharacterTextSplitter( chunk_size=512, chunk_overlap=50 ) # ChromaDB 클라이언트 및 컬렉션 설정 chroma_client = chromadb.Client() collection_name = "faq_data_collection" try: # 이미 존재하는 컬렉션인지 확인하고, 있으면 가져옴 collection = chroma_client.get_collection(name=collection_name) except chromadb.errors.CollectionNotFoundError: # 컬렉션이 존재하지 않을 경우에만 생성 collection = chroma_client.create_collection(name=collection_name) # Vector DB에서 유사 질문 검색 (ChromaDB) def find_similar_question_in_vector_db(new_question_embedding, collection, k=5): results = collection.query(query_embeddings=[new_question_embedding], n_results=k, include=['documents', 'metadatas', 'embeddings']) best_similarity = 0 best_question = None best_answer = None # 검색 결과에서 각 질문의 유사도와 답변을 처리합니다. if 'documents' in results and 'metadatas' in results: documents = results['documents'][0] metadatas = results['metadatas'][0] embeddings = results['embeddings'][0] for i in range(len(documents)): stored_embedding = embeddings[i] metadata = metadatas[i] if stored_embedding is not None: # 코사인 유사도를 통해 유사도를 계산합니다. similarity = cosine_similarity([new_question_embedding], [stored_embedding])[0][0] print(f"유사도: {similarity} for {documents[i]}") # 유사도가 가장 높은 결과를 선택하며, 임계값 이상일 경우에만 선택 if similarity > best_similarity and similarity >= SIMILARITY_THRESHOLD: best_similarity = similarity best_question = documents[i] if isinstance(metadata, list): metadata = metadata[0] best_answer = metadata.get('answer') if isinstance(metadata, dict) else None return best_question, best_answer # Fine-tuned GPT를 사용해 새로운 답변 생성 def gpt_generate_response_from_finetuned_gpt(question, style="의사 A 말투"): prompt = f"다음은 환자의 질문입니다: \"{question}\". 아래 말투를 사용하여 질문에 대해 성실하고 정확한 답변을 작성해주세요.\n\ 말투: {style}" response = client.chat.completions.create( model="", # Fine-tuned된 GPT 모델 ID messages=[ {"role": "system", "content": "You are a helpful medical assistant."}, {"role": "user", "content": prompt}, ], max_tokens=300, temperature=0.7, # 답변의 다양성을 조절합니다. ) return response.choices[0].message.content.strip() # 새로운 질문 처리 및 최종 응답 생성 def generate_final_response(new_question, collection): # 텍스트 스플리팅 및 임베딩 생성 splitted_texts = text_splitter.split_text(new_question) new_question_embedding = np.mean(embedding_function.embed_documents(splitted_texts), axis=0) # ChromaDB에서 유사 질문 검색 similar_question, answer = find_similar_question_in_vector_db(new_question_embedding, collection) if similar_question and answer: final_response = f"질문: {new_question}\n유사 질문: {similar_question}\n기본 답변: {answer}" else: generated_answer = gpt_generate_response_from_finetuned_gpt(new_question) final_response = f"질문: {new_question}\nGPT로 생성된 답변: {generated_answer}\n(이 답변은 벡터데이터에서 유사한 답변을 찾을 수 없어 GPT에 의해 생성되었습니다.)" return final_response # 사용자로부터 새로운 질문 입력 받기 new_question = input("새로운 질문을 입력하세요: ") # 최종 응답 생성 response = generate_final_response(new_question, collection) print(response) 로 데이터베이스에서 유사한 질문-답변 쌍을 끌어오려는데 정확히 같은 질문을 넣어도 (이러면 유사도가 1인데) 저장되어있는 답변이 끌어와지질 않네요...

개발자

#llm#rag

답변 1

댓글 0

조회 99

7달 전 · 익명 님의 질문

파이참 관련 질문드립니다

import pandas as pd import pyautogui score_A = 0 #쾌락 score_B = 0 #사회적환경 score_C = 0 #보복심리 question1 = pyautogui.prompt('난 가정 폭력을 당한적 있다.') #질문1 if question1 == "o": #만약 질문1에 맞다고 대답 한다면 score_B += 1 #환경에 1점 추가 score_C += 1 #보복심리에 1점추가 question2 = pyautogui.prompt('난 학교 폭력을 당한적 있다.') #질문2 if question2 == "o": #만약 질문2에 맞다고 대답한다면 score_B += 1 #환경에 1점추가 score_C += 1 #보복심리에 1점추가 question3 = pyautogui.prompt('난 여아가 이성적 으로 좋다.') #질문3 if question3 == "o": #만약 질문3에 맞다고 대답한다면 score_A += 1 #쾌락에 1점추가 question4 = pyautogui.prompt('난 살인을 할때 쾌락을 느낀다.') #질문4 if question4 == "o": #만약 질문4에 맞다고 대답한다면 score_A += 1 #쾌락에 1점추가 question5 = pyautogui.prompt('나의 범죄는 충동적 이였다.') #질문5 if question5 == "o": question6 = pyautogui.prompt('난 반 사회적 인격 장애를 진단 받은적 있다.') #질문6 if question6 == "o": #질문6에 맞다고 대답한다면 score_A += 1 #쾌락에 1점추가 score_C += 1 #사회적환경에 1점추가 question7 = pyautogui.prompt('나의 인간관계는 좋지않다.') #질문7 if question7 == "o": #질문7에 맞다고 대답한다면 score_B += 1 #사회적환경에 1점추가 question8 = pyautogui.prompt('난 예전에 아동범죄 피해자였다.') #질문8 if question8 == "o": #만약 질문10에 맞다고 대답한다면 score_C += 1 #보복심리에 1점추가 question9 = pyautogui.prompt('나의 범죄는 계획적이였다.') #질문9 if question9 == "o": #질문9에 맞다고 대답했을때 if question5 == "o": #질문5에도 맞다고 대답한다면 print("설문자가 솔직하게 문항에 답하고있지 않습니다.") #설문자가 제대로 설문에 응하고 있지 않다고 판단. answer_list = [] answer_list.append(question1) answer_list.append(question2) answer_list.append(question3) answer_list.append(question4) answer_list.append(question5) answer_list.append(question6) answer_list.append(question7) answer_list.append(question8) answer_list.append(question9) answer_list.append(question10) print(answer_list) survey_dict= {'문항번호': [1,2,3,4,5,6,7,8,9,10], '내용': answer_list, } survey_df = pd.DataFrame(survey_dict).set_index("문항번호") print(survey_df) 이 코드에서 IndentationError: expected an indented block after 'if' statement on line 23 이런 오류코드가 뜨는데 어떤 이유때문일까요?

개발자

#코딩

#파이참

#오류코드

답변 0

댓글 0

조회 11

7달 전 · 익명 님의 질문

파이참 관련 질문 드립니다.

IndentationError: expected an indented block after 'if' statement on line 23 이 오류코드가 뜨는 이유가 뭘까요?

개발자

#코딩

#파이참

#오류코드

답변 0

댓글 0

조회 10

7달 전 · 익명 님의 질문

파이참 코딩 관련 질문

import pandas as pd import pyautogui score_A : 0 #단순 쾌락 score_B : 0 #경제 적압박 score_C : 0 #사회 적압박 score_D : 0 #유전 score_E : 0 #보복 score_F : 0 #환경 question1 = pyautogui.prompt('난 가정 폭력을 당한적 있다.') #질문1 if question1 == "o": #만약 질문1에 맞다고 대답 한다면 score_E += 1 #환경에 1점 추가 score_D += 1 #유전에 1점 추가 question2 = pyautogui.prompt('난 학교 폭력을 당한적 있다.') question3 = pyautogui.prompt('난 여아가 이성적 으로 좋다.') question4 = pyautogui.prompt('난 가정 형편 또는 개인 적인 형편이 좋지 않다.') question5 = pyautogui.prompt('나의 범죄는 충동적 이였다.') question6 = pyautogui.prompt('난 반 사회적 인격 장애를 진단 받은적 있다.') question7 = pyautogui.prompt('난 대인 관계에 능통치 못하다.') question8 = pyautogui.prompt('난 감정 기복이 심하다.') question9 = pyautogui.prompt('나의 범죄는 계획적 이였다.') question10 = pyautogui.prompt('난 주변에 친한 사람이 없다.') answer_list = [] answer_list.append(question1) answer_list.append(question2) answer_list.append(question3) answer_list.append(question4) answer_list.append(question5) answer_list.append(question6) answer_list.append(question7) answer_list.append(question8) answer_list.append(question9) answer_list.append(question10) print(answer_list) survey_dict= {'문항번호': [1,2,3,4,5,6,7,8,9,10], '내용': answer_list, } survey_df = pd.DataFrame(survey_dict).set_index("문항번호") print(survey_df) 이 코드에서 NameError: name 'score_E' is not defined 라는 오류가 자꾸 뜨는데 왜때문인가요??ㅠㅠ

개발자

#파이참

#코딩

#심리테스트

답변 0

댓글 0

조회 19

7달 전 · 익명 님의 질문

파이참 코딩 관련 질문

score_A : 0 #단순 쾌락 score_B : 0 #경제 적압박 score_C : 0 #사회 적압박 score_D : 0 #유전 score_E : 0 #보복 score_F : 0 #환경 question1 = input('난 가정 폭력을 당한적 있다.') #질문1 if question1 == "o": #만약 질문1에 맞다고 대답 한다면 score_E += 1 #환경에 1점 추가 score_D += 1 #유전에 1점 추가 question2 = pyautogui.prompt('난 학교 폭력을 당한적 있다.') question3 = pyautogui.prompt('난 여아가 이성적 으로 좋다.') question4 = pyautogui.prompt('난 가정 형편 또는 개인 적인 형편이 좋지 않다.') question5 = pyautogui.prompt('나의 범죄는 충동적 이였다.') question6 = pyautogui.prompt('난 반 사회적 인격 장애를 진단 받은적 있다.') question7 = pyautogui.prompt('난 대인 관계에 능통치 못하다.') question8 = pyautogui.prompt('난 감정 기복이 심하다.') question9 = pyautogui.prompt('나의 범죄는 계획적 이였다.') question10 = pyautogui.prompt('난 주변에 친한 사람이 없다.') answer_list = [] answer_list.append(question1) answer_list.append(question2) answer_list.append(question3) answer_list.append(question4) answer_list.append(question5) answer_list.append(question6) answer_list.append(question7) answer_list.append(question8) answer_list.append(question9) answer_list.append(question10) print(answer_list) survey_dict= {'문항번호': [1,2,3,4,5,6,7,8,9,10], '내용': answer_list, } survey_df = pd.DataFrame(survey_dict).set_index("문항번호") print(survey_df) 위의 코드에서 NameError: name 'score_E' is not defined 라고 오류가 나는 이유가 뭘까?

개발자

#파이참

#코딩

#심리테스트

답변 0

댓글 0

조회 23

9달 전 · 유호준 님의 질문

NavigationContainer 중첩 오류

안녕하세요, RN(Expo)로 React Navigation을 적용하다 오류가 해결되지 않아서 질문드립니다. expo를 통해 다음과 같이 index.js에 React Navigation을 적용했습니다. import { store } from "@/redux/store"; import MainScreen from "./screens/MainScreen"; import { Provider } from "react-redux"; import { NavigationContainer } from "@react-navigation/native"; import { createNativeStackNavigator } from "@react-navigation/native-stack"; import LoginScreen from "./screens/LoginScreen"; export default function HomeScreen() { const Stack = createNativeStackNavigator(); return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Main" component={MainScreen} /> <Stack.Screen name="Login" component={LoginScreen} />{" "} </Stack.Navigator> </NavigationContainer> </Provider> ); } 그러나 다음과 같은 오류가 뜨며 빈화면만 보이더라구요ㅠ Error: Looks like you have nested a 'NavigationContainer' inside another. Normally you need only one container at the root of the app, so this was probably an error. If this was intentional, pass 'independent={true}' explicitly. Note that this will make the child navigators disconnected from the parent and you won't be able to navigate between them. 찾아보니 NavigationContainer가 중첩되었다는 것 같은데, 저는 계속해서 그대로 강의를 따라가고 있었고, 따로 NavigationContainer를 적용한 파일이 존재하지 않습니다 ㅠ 다음 속성을 추가해도 오류가 해결되지 않습니다 ㅠ 아마 어디선가 부모에서 NavigationContainer가 적용된 것 같은데 찾을 수가 없네요 ㅠㅠ independent={true} 조금 더 찾아보니 expo-router랑 충돌이 난 거일 수도 있다는데 정확하게 모르겠네요 ㅠ

개발자

#react-native

#react-navigation

#expo

#navigationcontainer

답변 0

댓글 0

조회 104

8달 전 · 노원재 님의 답변 업데이트

ReactNative ios build 에러 3일째 해결을 못했습니다.

시뮬레이션을 실행하려고 해도 스크립트 문제, iPhone 버전 범위 문제, 시뮬레이터 문제가 계속 발생합니다. 어떤 도움이라도 감사합니다. ReactNative를 처음 접했습니다. 저희 팀에서 저를 도울 수 있는 사람이 없습니다. #프로젝트 환경 mac M2 ruby -v ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin23] node -v v20.10.0 pod --version 1.15.2 package.json { "name": "labts", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint .", "start": "react-native start", "test": "jest" }, "dependencies": { "@react-native-community/async-storage": "^1.12.1", "@react-native-community/cli": "13.6.9", "@react-navigation/bottom-tabs": "^6.6.0", "@react-navigation/native": "^6.1.17", "@react-navigation/native-stack": "^6.10.0", "@tanstack/react-query": "^5.51.5", "@types/react-native-vector-icons": "^6.4.18", "axios": "^1.7.2", "date-fns": "^3.6.0", "immer": "^10.1.1", "react": "18.2.0", "react-native": "0.74.3", "react-native-calendars": "^1.1305.0", "react-native-date-picker": "^5.0.4", "react-native-dotenv": "^3.4.11", "react-native-get-random-values": "^1.11.0", "react-native-image-crop-picker": "^0.41.2", "react-native-image-zoom-viewer": "^3.0.1", "react-native-paper": "^5.12.3", "react-native-permissions": "^4.1.5", "react-native-safe-area-context": "^4.10.8", "react-native-screens": "^3.32.0", "react-native-splash-screen": "^3.3.0", "react-native-tab-view": "^3.5.2", "react-native-vector-icons": "^10.1.0", "react-native-vision-camera": "^4.5.1", "uuid": "^10.0.0", "yarn": "^1.22.22" }, "devDependencies": { "@babel/core": "^7.20.0", "@babel/preset-env": "^7.20.0", "@babel/runtime": "^7.20.0", "@react-native/babel-preset": "0.74.85", "@react-native/eslint-config": "0.74.85", "@react-native/metro-config": "0.74.85", "@react-native/typescript-config": "0.74.85", "@types/react": "^18.2.6", "@types/react-native-dotenv": "^0.2.2", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.6.3", "babel-plugin-module-resolver": "^5.0.2", "eslint": "^8.19.0", "jest": "^29.6.3", "prettier": "2.8.8", "react-test-renderer": "18.2.0", "typescript": "5.0.4" }, "engines": { "node": ">=18" } } PodFile require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, '12.0' use_frameworks! #use_modular_headers! prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] if linkage != nil Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green use_frameworks! :linkage => linkage.to_sym end target 'nexlabts' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) target 'nexlabtsTests' do inherit! :complete # Pods for testing end post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( installer, config[:reactNativePath], :mac_catalyst_enabled => false, # :ccache_enabled => true ) end end 제가 아래 에러 3가지에 대해 제가 해본 방법들입니다. 1. node 재설치 node_module 폴더 삭제, package-rock.json 삭제 후 재설치 npm install --legacy-peer-deps yarn install 2. Xcode가 node 읽을 수 있도록 설정 sudo ln -s "$(which node)" /usr/local/bin/node 3. Podfile 내 platform 설정 수정 platform :ios, '12.0' or platform :ios, '14.0' 4. Pods 재설치 rm -rf ~/Library/Developer/Xcode/DerivedData or rm -rf ~/Library/Developer/Xcode/DerivedData/* rm -rf Pods rm Podfile.lock pod install --repo-update Xcode \> Product \> Clean Build Folder. cd ./ios pod cache clean -all pod install --repo-update cd ../ npx react-native run-ios --no-packager --simulator="iPhone 15" or npx react-native run-ios --simulator="iPhone 15" or yarn start > i(run ios) Err 1. cocoaPods 설치할 때 [!] CocoaPods could not find compatible versions for pod "React-RuntimeHermes": In Podfile: React-RuntimeHermes (from ../node_modules/react-native/ReactCommon/react/runtime) Specs satisfying the React-RuntimeHermes (from ../node_modules/react-native/ReactCommon/react/runtime) dependency were found, but they required a higher minimum deployment target. Err2. iOS 실행할때 run-ios --no-packager --simulator="iPhone 15" Build description signature: fc1341421f84b87c5245d346c2c17b66 Build description path: /Users/nowonjae/Library/Developer/Xcode/DerivedData/nexlabts-argvodqcybjfcybstpulfpghnzvm/Build/Intermediates.noindex/XCBuildData/fc1341421f84b87c5245d346c2c17b66.xcbuilddata /Users/nowonjae/Desktop/project/NeXLabRN/ios/nexlabts.xcodeproj:1:1: error: Unable to open base configuration reference file '/Users/nowonjae/Desktop/project/NeXLabRN/ios/Pods/Target Support Files/Pods-nexlabts/Pods-nexlabts.release.xcconfig'. (in target 'nexlabts' from project 'nexlabts') warning: Unable to read contents of XCFileList '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Unable to read contents of XCFileList '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-input-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase 'Bundle React Native code and images' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase '[CP] Embed Pods Frameworks' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-input-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase '[CP] Copy Pods Resources' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') --- xcodebuild: WARNING: Using the first of multiple matching destinations: { platform:iOS Simulator, id:B5AA2E84-4F83-4749-A986-A1FCE5E398A3, OS:17.5, name:iPhone 15 } { platform:iOS Simulator, id:B5AA2E84-4F83-4749-A986-A1FCE5E398A3, OS:17.5, name:iPhone 15 } ** BUILD FAILED ** ] Err3. Xcode 로 Build 할때 (Any iOS Simulator Device (arm64, x86_64)) Command PhaseScriptExecution failed with a nonzero exit code

개발자

#reactnative

#xcode

#reactnative-run-ios

답변 1

댓글 0

조회 535

9달 전 · 익명 님의 질문

Spring boot 네이버페이 연동하기

스프링 부트 프로젝트를 개발 중인데 네이버 페이를 붙이려고 합니다. 카카오페이는 WebClient 방법으로 완료 하였구요 네이퍼 페이도 같은 방법으로 구현 하려고 하는데 등록된 파트너가 없습니다로만 나옵니다. 네이버페이 개발자센터에서는 SDK를 제공한다고 되어있어서 이게 프론트단에서 진행 되야하는건지 잘 모르겠습니다. 결제서버를 구축중이라 서버쪽에서만 하려고 하는데 블로그글도 많이없어 찾기가 어렵더라구요ㅠㅠ https://dev.apis.naver.com/{partnerId}/naverpay/payments/v2/payment_ready 경로를 이렇게 보내고 있는데요 {error_code=052, message=?? : Partner does not exists. (등록된 파트너가 없습니다.)} 이런 결과가 반환되고 있습니다.. 무슨 문제인지 해결방법을 알고 계신다면 조언 부탁드릴께요 네이버페이 샌드박스 가맹점의 가맹점 Id를 사용하는데 안되는게 이상합니다...

개발자

#spring-boot

#naver-api

답변 0

댓글 0

조회 150

9달 전 · 포크코딩 님의 새로운 댓글

Next.js Dynamic Routing 관련 질문

현재 ./pages 폴더에서 page router로 라우팅 관리 중에 있습니다! id별 post 상세창 조회를 위해 ./pages/post-detail/[id].tsx 와 같이 작성했으나 Whitelabel Error Page This application has no configured error view, so you are seeing this as a fallback. Fri Aug 30 21:08:21 KST 2024 [67199a4f-4509] There was an unexpected error (type=Not Found, status=404) 만 발생합니다 참고로 ./pages/post-write.tsx 와 같은 파일은 정상 작동합니다 혹시 무엇이 문제일까요? 추가+) 혹시 Next.js 14에서 page router 방식을 사용하는것이 문제일지 궁금합니다

개발자

#react

#next.js

답변 1

댓글 2

조회 52

9달 전 · 백승훈 님의 새로운 답변

Next.js 사용 시 SyntaxError: Expected property name or '}' in JSON at position 61의 에러위치가 어딘지 어떻게 알수있나요?

"next-auth": "^5.0.0-beta.20" 사용 중인데 해당 에러를 검색해보니 JSON 형식의 문자열이 아니기 때문에 에러가 발생한 것이라고 하던데 에러가 일어난 코드의 위치를 정확히 말을 안해주니 어디서 어떻게 고쳐야할지 도통 모르겠습니다....ㅠㅠ 해당 에러를 야기하는 것으로 의심되는 파일의 코드와 에러메시지를 띄운 터미널을 캡처하여 첨부드립니다... 혹시 어디서 문제인지 힌트라도 주신다면 열심히 찾아 해결해보겠습니다!!!

개발자

#next-auth

#next.js

답변 1

댓글 0

조회 48

10달 전 · 익명 님의 질문

Expo SQLite WHERE 조건 한글 안됨

React Native Expo에서 앱을 개발중에 sql문이 오류가 뜹니다. 코드는 아래와 같습니다. async function SearchName() { console.log("load data"); try { const db = await SQLite.openDatabaseAsync("MountBedge.db"); const data = await db.getAllAsync(`SELECT * FROM HikingData WHERE Name = '가';`); setLoadedData(data); } catch (error) { console.error("Error testing database connection:", error); } } 문제가 되는 부분은 getAllAsync의 WHERE부분입니다. 한글로 검색한 부분을 영어로 변경하면 오류도 뜨지 않고 검색도 잘 됩니다. 한글로 검색 시 뜨는 오류는 아래와 같습니다. Error testing database connection: [Error: Calling the 'prepareAsync' function has failed → Caused by: Error code 1: near "'ㄱ'": syntax error] 혹시 해결할 방법을 아시는 분이 계시나요? 이게 expo에서는 해결이 가능한건지, 아니면 react native cli로 넘어가야 하는건지 모르겠습니다. 추가로 expo에서 sql문으로 데이터를 저장 시 db가 어디에 있는지 알 수 있는 방법이 있다면 알고싶습니다. 영어를 못해 영어로는 검색을 거의 안해봤지만 자료가 너무 없네요...

개발자

#react-navite-expo

#react-native

#expo

#sql

답변 0

댓글 0

조회 50

10달 전 · 문정동개발자 님의 새로운 답변

웹폰트 나눔스퀘어네오 윈도우 크롬 적용안되는 현상

React 프로젝트이며, 웹폰트로 나눔스퀘어네오 cdn방식으로 가져오고 있습니다. 맥에서는 잘 적용되는데, 윈도우 크롬 콘솔에 에러 뜨고 네트워크탭 - 폰트 확인 시 404가 뜨는데, 혹시 저와 같은 현상인 분 있으신가요?? 콘솔 에러 OTS parsing error: Unable to instantiate font face from font data. ``` @font-face { font-family: 'NanumSquareNeo-Variable'; src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_11-01@1.0/NanumSquareNeo-Variable.woff2') format('woff2'), url('https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_11-01@1.0/NanumSquareNeo-Variable.woff') format('woff'); font-weight: normal; font-style: normal; } ``` 나눔스퀘어네오 폰트 https://noonnu.cc/font_page/1053

개발자

#프론트엔드

#react

#fronted

#font

#웹폰트

답변 1

댓글 0

보충이 필요해요 1

조회 209

일 년 전 · 익명 님의 질문 업데이트

마이크로 프론트 구현(Nextjs, React)

요구사항 마이크로 프론트엔드로 A라는 프로젝트에서 B라는 프로젝트의 컴포넌트를 사용하고 싶다 프로젝트 설명 ModuleFederationPlugin 사용해서 expose remote 설정 A 프로젝트 (remote) : react, styled-component 사용 B 프로젝트 (expose) : nextjs, scss 사용 첫번째 오류 styled 이 달라서 nextjs 에서 노드가 불러와지지 않는 것 해결 : <noscript id="**next_css__DO_NOT_USE**"></noscript> → 두번째 오류 발생 오류 내용 Cannot read properties of null (reading 'parentNode') TypeError: Cannot read properties of null (reading 'parentNode') at options.insert (webpack- 두번째 오류 Nextjs 에서 expose 할 때 Page 컴포넌트에 있는 useState를 사용 못한다고함 해결 : peerDependencies 로 nextjs 추가 → 오류동일 오류 내용 TypeError: Cannot read properties of null (reading 'useState') at useState (react.development.js:1623:21) at Page (index.js:8:40) react-dom.development.js:18704 The above error occurred in the <Page> component: 참고 : https://dev.to/omher/building-react-app-with-module-federation-and-nextjsreact-1pkh 두번째 오류를 해결해야 되는데 가능한 방법인지 모르겠습니다. 아시는 분은 댁글 남겨주세요~(코드상에 보안상 문제되는 부분은 a b 로 바꿨습니다.

개발자

#micro-frontend-architecture

#react

#next.js

#modulefederationplugin

답변 0

댓글 0

조회 283

일 년 전 · 삭제된 사용자 님의 댓글 업데이트

안녕하세요.. 정말 이것저것 다 해봤는데 안되네요 ㅠ

안녕하세요. 리액트와 리액트 쿼리를 이용해 프로젝트를 진행 중 입니다. 저는 일단. src/hooks/useProduct.jsx 라는 커스텀 훅 을 만들었습니다. 제 계획은 1. 맨 처음 최상단 Home.jsx 에서 useProduct 라는 커스텀 훅 호출 2. 자식컴포넌트에 data를 전달 3. Search.jsx에서 받은 filter값으로 커스텀 훅 안의 query 재실행 4. 바뀐 상태는 Home.jsx 가 다시 받고 자식 컴포넌트에게 전달. 1~3까지는 콘솔찍어가면서 잘 되는데 4.는 되지 않습니다. (쿼리 데이터가 바뀌어도 4이 재 실행이 안됨..) ㅠㅠㅠㅠㅠㅠㅠ 쿼리 옵션도 줘보고 전역 상태도 만들어보고 이것저것 다 해봤는데 ㅠㅠ 혹시 아시는분 계신가요..? 어떠한 답변도 정말 감사히 받겠습니다 간략 코드첨부) Home.jsx const Home = ()=>{ const { data, error, isLoading } = useProduct(); return ( <Search /> <List data={data?.product} /> ); }; export default Home; Search.jsx const Search = () => { ```일부코드생략``` const { updateQuery } = useProduct (); const handleSubmit = () => { const searchData = { productId }; updateQuery(productId); }; } return( ```일부코드생략``` <button onClick={handleSubmit}> 조회 </button> ) } export default Search; useProduct.jsx const useProduct = () => { const [queryData, setQueryData] = useState(); const { data, error, isLoading } = useQuery({ queryKey: ["product", queryData], queryFn: () => fetchProduct(queryData), }); const updateFilters = (queryData) => { setQueryData(() => (queryData); }; return { data, error, isLoading, updateQuery , }; export default useProduct ;

개발자

#react

#react-query

#react-query-v5

답변 3

댓글 6

조회 116

일 년 전 · 우엉김밥 님의 질문 업데이트

react-query,

안녕하세요. 리액트쿼리 최신v5를 사용하면서 어려움에 처해 글을 남기게 되었습니다. 제가 만든 코드는 아래와 같습니다. Home.jsx (맨처음 데이터를 받아서 List에 뿌려주는 역할) const { data, error, isLoading } = useFilteredApartmentData(); console.log('home data',data) <List data={data.speechCommands} /> Search.jsx (사용자 검색) const { updateFilters } = useFilteredApartmentData(); //커스텀훅 const handleSubmit = (filter) => { updateFilters(filter); }; useFilteredApartmentData .jsx (훅) const useFilteredApartmentData = () => { const [filters, setFilters] = useState({ skip: 0, take: 15 }); const { data, error, isLoading } = useQuery({ queryKey: ["apartments", filters], queryFn: () => fetchFilteredApartmentData(filters), placeholderData: keepPreviousData, enabled: !!filters, }); console.log("훅안에서 새로운데이터", data); const updateFilters = (newFilters) => { console.log(newFilters); setFilters((prevFilters) => ({ ...prevFilters, ...newFilters, })); }; return { data, error, isLoading, updateFilters, }; }; export default useFilteredApartmentData; 저의 계획은 search.jsx에서 사용자의 검색을 받으면 훅의 updateFilters 를 실행시키고 useState가 바뀌니 useQuery의 재 시작과 함께 새로운 데이터를 받아 List에서 새로운 데이터를 뿌리는 것이었습니다. 그런데 console.log("훅안에서 새로운데이터", data); 이 부분도 새로운 데이터로 잘 찍히는데 문제는 Home.jsx 에서 console.log('home data',data) 이부분은 안찍히네요 결과적으로, 리스트의 변동이 없습니다. 혹시 아시는분 답변주시면 정말 감사하겠습니다 ㅠㅠ

개발자

#react

#react-query

답변 0

댓글 0

조회 77

일 년 전 · 포크코딩 님의 새로운 댓글

리액트쿼리 데이터 리패칭 이렇게 하는거 아닌가요?

home.jsx const { data, error, isLoading } = useFilteredApartmentData(); <List data={data.result} /> 훅.jsx const useFilteredApartmentData = () => { const queryClient = useQueryClient(); const [filters, setFilters] = useState({ skip: 0, take: 15 }); const { data, error, isLoading } = useQuery({ queryKey: ["aaa", filters], queryFn: () => fetchFilteredApartmentData(filters), placeholderData: keepPreviousData, enabled: !!filters, }); const mutation = useMutation({ mutationFn: (filter) => { fetchFilteredApartmentData(filter); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["aaa", filters] }); }, }); const updateFilters = (newFilters) => { console.log(newFilters); setFilters(newFilters); mutation.mutate(newFilters); }; return { data, error, isLoading, updateFilters, }; }; export default useFilteredApartmentData; 여기서 처음에 데이터 패칭은 잘 이루어 지는데 fillter가 바뀌면 훅의 updateFilters 가 동작하여 새로운 데이터를 list에 다시 뿌리려고하는데 화면에 변화가 없습니다 ㅜㅜ 이렇게 하는거 아닌가요??

개발자

#react

#react-query

답변 1

댓글 2

조회 68

일 년 전 · 김하늘 님의 새로운 답변

Next.js axios patch메서드 cors error

현재 마이스터고 재학 중인 2학년 학생입니다. 학교에서 Next.js를 사용하여서 서비스를 만드는 프로젝트를 하고있습니다 이 프로젝트 중 서버와의 통신을 위한 axios를 customAxios로 만들었고 기존 put메서드로 수정 api를 호출했을 당시엔 요청이 갔는데 patch메서드로 하니 CORS에러가 계속 뜹니다. velog와 wrtn등을 이용하여 withCredentials: true도 줘보고 package.json에 "proxy"도 줘봤는데 계속 CORS에러가 뜨네요.. 혹시 몰라서 postman으로 호출했을때는 정상적으로 호출이 가는데 이 경우는 무엇이 문제일까요? 도와주시면 감사하겠습니다.. ㅠㅠ

개발자

#corserror

#next.js

#react

#frontend

답변 1

댓글 0

조회 96

일 년 전 · 최용빈 님의 답변 업데이트

파이썬 오류 좀 고쳐주세요 ㅠㅠ

import time import requests import streamlit as st API_BASE_URL = "http://localhost:8000/qna" # Fastapi로 api 생성 def request_chat_api(user_message: str) -> str: url = API_BASE_URL resp = requests.post( url, json={ "user_message": user_message, }, ) resp = resp.json() print(resp) return resp["answer"] def init_streamlit(): st.set_page_config(page_title='Dr. KHU', page_icon='🩺') if "messages" not in st.session_state: st.session_state.messages = [{"role": "assistant", "content": "안녕하세요! Dr.seo입니다🩺"}] # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages from history on app rerun for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) def chat_main(): if message := st.chat_input(""): # Add user message to chat history st.session_state.messages.append({"role": "user", "content": message}) # Display user message in chat message container with st.chat_message("user"): st.markdown(message) # Display assistant response in chat message container assistant_response = request_chat_api(message) with st.chat_message("assistant"): message_placeholder = st.empty() full_response = "" for lines in assistant_response.split("\n"): for chunk in lines.split(): full_response += chunk + " " time.sleep(0.05) # Add a blinking cursor to simulate typing message_placeholder.markdown(full_response) full_response += "\n" message_placeholder.markdown(full_response) # Add assistant response to chat history st.session_state.messages.append( {"role": "assistant", "content": full_response} ) if __name__ == "__main__": init_streamlit() chat_main() 이 코드를 실행시키면 자꾸 AttributeError: st.session_state has no attribute "messages". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization 라고 뜨네요..

개발자

#파이썬

#python

답변 2

댓글 1

보충이 필요해요 2

조회 347

일 년 전 · 김유진 님의 새로운 댓글

리액트에서 superagent를 활용해서 minio에 업로드하는 방법을 알려주세요 😂

제발 도와주세요 ㅜㅜㅜㅜㅜ 몇일동안 오류를 해결하지 못하고 있어요.. .. 리액트 웹에서 모바일 핸드폰으로 웹을 접속했을 경우, input을 통해서 사진을 업로드하거나 촬영한 이미지를 minio에 업로드 하고 싶은데, 아래 부분에서 계속 오류가 발생해서 도움을 요청해요 ㅠㅠ https://min.io/docs/minio/linux/developers/javascript/API.html#presignedPostPolicy 위 문서를 참고해서 코드를 작성했어요! [핸드폰으로 웹 접속 -> 사진 업로드/촬영 -> minio 업로드] 이 순서인데, minio에 이미지가 업로드가 되지 않고 계속 오류를 발생시켜요. superagent를 활용해서 minio에 업로드가 가능하다고, 위 문서를 참고해서 작성을 했는데, 계속 아래 에러 메시지를 전달받고 있어요ㅜㅜ 아래 에러를 게속 반환해요. <Error> <Code>MalformedPOSTRequest</Code> <Message>The body of your POST request is not well-formed multipart/form-data. (The name of the uploaded key is missing)</Message> <BucketName>bucket</BucketName> <Resource>/bucket</Resource> <RequestId>RequestId...</RequestId> <HostId>HostId...</HostId> </Error> f12 개발자 모드 페이로드 전달 데이터 bucket: 데이터 Content-Type: multipart/form-data x-amz-date: 날짜정보 x-amz-algorithm:데이터 x-amz-credential: 데이터 policy: 데이터 x-amz-signature: 데이터 file: (바이너리)

개발자

#react

#superagent

#typescript

답변 1

댓글 2

조회 73

일 년 전 · 문종호 님의 답변 업데이트

VS CODE import error

tensorflow는 이미 설치 완료한 상태인데 이 부분이 계속 문제 있다고 뜨는데 해결방법을 도저히 모르겠어요ㅠㅠ

개발자

#vscode

#python

#import

#tensorflow

답변 1

댓글 0

추천해요 1

조회 38

일 년 전 · 신진철 님의 새로운 댓글

우분투에서 pip install 시, 다음과 같은 오류가 발생합니다.

안녕하십니까 선배님들. 현재 AWS EC2에서 안드로이드 어플리케이션 용으로 백엔드 서버를 구축하는 도중, 다음과 같은 오류를 맞이했습니다. 현재 사용하는 ubuntu는 24.04 LTS 버전입니다. 도무지 해결 방안을 찾지 못해서 이렇게 조언을 구하고 싶습니다. 감사합니다. pip install git error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install. If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv. Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed. If you wish to install a non-Debian packaged Python application, it may be easiest to use pipx install xyz, which will manage a virtual environment for you. Make sure you have pipx installed. See /usr/share/doc/python3.12/README.venv for more information. note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification.

개발자

#서버

#ec2

#ubuntu

답변 2

댓글 2

추천해요 1

조회 817

일 년 전 · 정창록 님의 질문

Next.js 에서 fluent-ffmpeg 사용 시 에러 해결 가능할까요?

Next.js 에서 puppeteer를 사용해서 특정 url에 접속하여 애니메이션을 png로 100장 정도 캡처하여 생성하고, fluent-ffmpeg를 사용해서 해당 png 이미지들을 mp4 영상으로 만들려고 하는데요. yarn add puppeteer fluent-ffmpeg @ffmpeg-installer/ffmpeg yarn add --dev @types/fluent-ffmpeg 위와 같이 라이브러리들을 설치했구요. 아래 page.tsx 파일에서 코드를 구현했는데요. dev로 실행해서 해당 페이지에 접속을 하면 아래와 같은 에러가 발생하는데요. 해결이 가능할까요?? 다른 라이브러리를 써야할지 구현한 코드가 문제가 있는지 모르겠네요. 도움 부탁드립니다!! # 에러 코드 # 1 of 1 error Next.js (14.2.3) Server Error Error: Cannot find module '/Users/.../animation-capture/node_modules/@ffmpeg-installer/darwin-arm64/package.json' This error happened while generating the page. Any console logs will be displayed in the terminal window. Call Stack webpackEmptyContext file:///Users/.../animation-capture/.next/server/app/capture/page.js (22:10) eval node_modules/@ffmpeg-installer/ffmpeg/index.js (40:27) (rsc)/./node_modules/@ffmpeg-installer/ffmpeg/index.js file:///Users/.../animation-capture/.next/server/vendor-chunks/@ffmpeg-installer.js (20:1) Next.js eval /./src/app/capture/page.tsx (rsc)/./src/app/capture/page.tsx file:///Users/.../animation-capture/.next/server/app/capture/page.js (286:1) Next.js # 코드 구현부 # import { NextApiRequest, NextApiResponse } from 'next'; import puppeteer from 'puppeteer'; import fs from 'fs'; import path from 'path'; import ffmpeg from 'fluent-ffmpeg'; import ffmpegInstaller from '@ffmpeg-installer/ffmpeg'; ffmpeg.setFfmpegPath(ffmpegInstaller.path); .... 중략.... const outputFilePath = path.resolve("./screenshots/video.mp4"); ffmpeg() .addInput(`${folderPath}/screenshot-%d.png`) .inputFPS(10) .output(outputFilePath) .on("end", () => { res.status(200).send(`Video created successfully at ${outputFilePath}`); }) .on("error", (err) => { console.error("Error generating video:", err); res.status(500).send("Failed to generate video"); }) .run(); } catch (error) { console.error("Error capturing screenshots:", error); res.status(500).send("Failed to capture screenshots"); }

개발자

#next.js

#fluent-ffmpeg

#mp4

답변 0

댓글 0

조회 94

일 년 전 · 김민준 님의 새로운 댓글

왜 이렇게 나올까요 ㅠㅠ 도와주세요 ㅠㅠ

Fatal Python error: init_import_site: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap>", line 980, in exec_module File "<frozen site>", line 626, in <module> File "<frozen site>", line 612,

개발자

#python3

답변 1

댓글 1

보충이 필요해요 2

조회 208

일 년 전 · 익명 님의 질문

이력서 스터디를 기획 중인데 피드백을 받고 싶습니다!

이력서 스터디를 진행하려고 합니다! 이력서 관련 영상들을 분석하고 정리해서 Cheet Sheet를 만들어보자! 라는 목표를 가지고 진행하려 합니다. 제가 보기엔 기획이 이정도면 됐다 생각이 되는데 다른분들이 보기엔 그렇지 않을 수 있을것 같아 피드백 받아보고 싶습니다! https://circular-error-a3d.notion.site/4e4b5aff884c478c99d2733bdfe73f42?pvs=4

개발자

#이력서

답변 0

댓글 0

조회 51

일 년 전 · 예빈 님의 새로운 댓글

타입스크립트 타입지정

리액트 쿼리로 OptimisticUpdate 를 구현했는데 onError 에서 context 타입 지정을 어떻게 해야할지 모르겠습니다 ㅠㅠ context : 타입 하면 오류나고, data : 타입 = context 해도 오류나고 as 를 쓰면 해결되긴 하는데 더 좋은 방법 없을까요? ㅠㅠㅠ 'use client'; import { useState } from 'react'; import { toast } from 'react-toastify'; import { usePostLikeCount } from '@/hooks'; interface LikeContextType { previousLikeCount: number; previousIsLike: boolean; } export const useOptimisticLike = ( boardId: number, initialLikeCount: number, initialIsLike: boolean, refetch: () => void ) => { const [optimisticLikeCount, setOptimisticLikeCount] = useState(initialLikeCount); const [optimisticIsLike, setOptimisticIsLike] = useState(initialIsLike); const { mutate: postMutate } = usePostLikeCount(boardId, { onMutate: async (): Promise<LikeContextType> => { setOptimisticLikeCount((prev) => optimisticIsLike ? prev - 1 : prev + 1 ); setOptimisticIsLike((prev) => !prev); return { previousLikeCount: optimisticLikeCount, previousIsLike: optimisticIsLike, }; }, onError: (err, variables, context) => { const data: LikeContextType = context; if (data) { setOptimisticLikeCount(data.previousLikeCount); setOptimisticIsLike(data.previousIsLike); } toast.error('좋아요 업데이트에 실패했습니다.'); }, onSuccess: () => { refetch(); }, }); const uploadLike = () => { postMutate(); }; return { optimisticLikeCount, optimisticIsLike, uploadLike, }; };

개발자

#react-query

#typescript

답변 1

댓글 1

조회 60

일 년 전 · 김하림 님의 새로운 답변

프론트 경력 기술 면접 궁금한 것이 있습니다.

안녕하세요 주니어 프론트엔드 개발자 입니다. 1. 기술면접에서 어떤 프로젝트의 기술적인 부분을 설명해달라고 했을 때 아래와 같이 기본적인 내용도 말할만 한가요? - 리액트의 Suspense 와 Error Boundary 를 사용하여 선언적으로 Data Fetching 을 처리함 Error fallback 에는 refetch 가능한 로직도 포함하여 재시도 할 수 있게끔 함. 2. 제가 도입하지 않은 라이브러리에 대해 도입 이유를 물어본다면 제가 생각한 도입 이유를 말해도 될까요? - 제가 도입했다고 말하지도 않았는데 이런 질문을 종종 받습니다. 기록이 따로 없었기 때문에 회사에서 그 라이브러리를 도입한 이유는 알 수는 없습니다. - 이야기할 때 진짜 이유는 모르지만 저라면 ~해서 도입했을 것 같습니다. 처럼 이야기 하는 편입니다.

개발자

#react

#이직

#프론트엔드

답변 2

댓글 0

추천해요 1

조회 581

일 년 전 · 유호준 님의 질문 업데이트

React-query로 실시간 데이터 반영

리액트를 통해 버스 위치 데이터를 받아서 버스 위치를 실시간으로 보여주는 앱을 개발하고 있는데요, 리액트 쿼리를 활용해 10초마다 refetch하여 데이터를 업데이트하려고 하는데 계속 자동으로 캐싱되어 처음 가져온 데이터만 10초마다 가져오네요 ㅠ (개발자 도구에서 disable cache를 하면 잘 가져옴) 새로고침를 해도 마찬가지 입니다. const { data, isLoading, error, refetch } = useQuery(["busPos"], getData, { refetchIntervalInBackground: true, refetchInterval: 10000, cacheTime: 10000, }); 어떻게 하면 데이터를 잘 업데이트할 수 있을까요?? Open api 사용 중인데 요청 헤더에 캐시 컨트롤을 노 캐시로 하면 cors 에러가 뜹니다 ㅠ

개발자

#react

#react-query

#cache

답변 1

댓글 0

조회 214

일 년 전 · 털먹는토끼 님의 댓글 업데이트

리액트 쿼리 에러 핸들링 이슈

react query를 활용한 에러 핸들링이 안돼서 질문 올립니다... //mainpage.tsx const { data, refetch, isFetching } = FetchData(url); const handleSearch = () => { refetch(); } <QueryErrorResetBoundary> {({ reset }) => ( <ErrorBoundary onReset={reset} FallbackComponent={FallbackUI}> {resultVisible ? ( <Result searchData={searchData} isFetching={isFetching} /> ) : ( <EmptyResult /> )} </ErrorBoundary> )} </QueryErrorResetBoundary> react-error-boundary 라이브러리를 이용해 ErrorBoundary 컴포넌트를 가져왔습니다. ErrorBoundary 하위 컴포넌트 내에서 에러가 발생하면 FallbackComponent의 FallbackUI 컴포넌트가 렌더링 되도록 했습니다. //FallbackUI 컴포넌트 //에러가 발생히면 이 컴포넌트가 렌더링되어야합니다. const FallbackUI = ({ error, resetErrorBoundary }) => { return ( <div> <span>{error.message}...</span> <button onclick={resetErrorBoundary} /> 돌아가기 버튼 </div> ); }; export default FallbackUI; FallbackUI 에서 QueryErrorResetBoundary 에서 제공하는 resetErrorBoundary를 받아와 에러 발생 후 '돌아가기 버튼'을 클릭하면 쿼리오류를 처리하고 리셋해주도록 구현했습니다. //url을 파라미터값으로 받아와 api호출하는 함수 //위에 있는 mainpage.tsx 에서 사용하는 함수입니다. const FetchData = (url: string) => { const { error, data, refetch, isFetching } = useQuery({ queryKey: ["repoData"], queryFn: async () => { const res = await axios.get(url); console.log(res.data); return res.data; }, refetchOnWindowFocus: false, enabled: false, }); return { error, data, refetch, isFetching }; }; 리액트 쿼리를 이용해 api를 호출하는 함수입니다. //main.tsx const queryClient = new QueryClient({ defaultOptions: { queries: { retry: 0, throwOnError: true, }, }, }); ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <QueryClientProvider client={queryClient}> <BrowserRouter> <GlobalStyles /> <Provider store={store}> <App /> </Provider> </BrowserRouter> </QueryClientProvider> </React.StrictMode> ); 마지막으로 전역으로 에러 관리를 하도록 세팅해놨습니다. 그리고 QueryClient에 throwOnError 속성이 있어야 에러를 ErrorBoundary로 전달할 수 있다해서 추가해줬습니다. 이렇게 세팅해놨는데 에러발생하면 그냥 하얀색 화면만 나오고 fallbackUI가 나오지 않습니다... 원인이 뭘까요...ㅠㅠㅠ 혹시 몰라서 콘솔 에러코드도 올립니다.. 추가로 궁금한 점 1. useQuery 에서 반환하는 객체중 error 객체는 어떤 존재인지 궁금합니다. 2. useQuery 속성과 QueryClient 속성 모두 throwOnError : true 를 가지고 있던데 어떤 차이점인지 궁금합니다. 답변주시면 정말 감사하겠습니다!!!

개발자

#react

#react-query

#error-handler

#error-boundary

답변 1

댓글 1

조회 212