Skip to content

Commit

Permalink
Merge pull request #42 from ktb-23/feat13/Fooddata
Browse files Browse the repository at this point in the history
Feat13/fooddata
  • Loading branch information
hardlife0 authored Sep 10, 2024
2 parents 4102292 + bdebe8d commit bbb2929
Show file tree
Hide file tree
Showing 6 changed files with 171 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/api/useGetFoodlog.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import api from '../config/apiConfig';

const useGetFood = async (date) => {
const accesstoken = localStorage.getItem('accesstoken');
try {
const response = await api.get(`/api/food_log/${date}`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accesstoken}`,
},
});
console.log(response.data); // 응답 데이터를 콘솔에 출력합니다.
return response.data; // 데이터를 반환합니다.
} catch (error) {
console.error('Error fetching food log:', error);
throw error; // 에러 발생 시 호출한 쪽에서 처리할 수 있도록 에러를 던집니다.
}
};

export default useGetFood;
20 changes: 20 additions & 0 deletions src/api/useInsertFoodLog.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import api from '../config/apiConfig';

const useInsertFood = async (body) => {
const accesstoken = localStorage.getItem('accesstoken');
try {
const response = await api.post('/api/food_log', body, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accesstoken}`,
},
});
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
return error;
}
};

export default useInsertFood;
19 changes: 19 additions & 0 deletions src/api/useSaveFoodLog.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import api from '../config/apiConfig';

const useSaveFoodLog = async (mealData) => {
const accesstoken = localStorage.getItem('accesstoken');
try {
const response = await api.post('/api/food_log', mealData, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accesstoken}`,
},
});
return response.data;
} catch (error) {
console.error('Error saving food log:', error);
throw error;
}
};

export default useSaveFoodLog;
20 changes: 20 additions & 0 deletions src/api/useUpdateFood.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import api from '../config/apiConfig';

const useUpdateFood = async (body, foodlog_id) => {
const accesstoken = localStorage.getItem('accesstoken');
try {
const response = await api.put(`/api/food_log/${foodlog_id}`, body, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accesstoken}`,
},
});
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
return error;
}
};

export default useUpdateFood;
File renamed without changes.
92 changes: 92 additions & 0 deletions src/hooks/useFood.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { useEffect, useState } from 'react';
import useGetFoodlog from '../api/useGetFoodlog';
import useInsertFood from '../api/useInsertFoodLog';
import useUpdateFood from '../api/useUpdateFood';

const useFood = (selectedDate) => {
const [foodId, setFoodId] = useState('');
const [logId, setLogId] = useState('');
const [dateId, setDateId] = useState('');
const [foodLogs, setFoodLogs] = useState([]);
const [mealTypes, setMealTypes] = useState(['아침', '점심', '저녁']);
const [kcal, setKcal] = useState({
아침: 0,
점심: 0,
저녁: 0,
});

const fetchFoodLogs = async () => {
try {
const response = await useGetFoodlog(selectedDate);
if (response.length > 0 && response[0].food) {
setFoodId(response[0].food_id);
setLogId(response[0].log_id);
setDateId(response[0].date_id);
setFoodLogs(response[0].food);

// 칼로리 계산
const newKcal = { 아침: 0, 점심: 0, 저녁: 0 };
response[0].food.forEach((log) => {
if (newKcal.hasOwnProperty(log.meal_type)) {
newKcal[log.meal_type] += parseFloat(log.kcal) || 0;
}
});
setKcal(newKcal);
} else {
setFoodId('');
setLogId('');
setDateId('');
setFoodLogs([]);
setKcal({ 아침: 0, 점심: 0, 저녁: 0 });
}
} catch (error) {
console.error('음식 데이터를 가져오는 중 오류 발생:', error);
setFoodId('');
setLogId('');
setDateId('');
setFoodLogs([]);
setKcal({ 아침: 0, 점심: 0, 저녁: 0 });
}
};

useEffect(() => {
fetchFoodLogs();
}, [selectedDate]);

const handleFoodUpload = async (mealType, foodData) => {
const uploadData = {
date: selectedDate,
meal_type: mealType,
...foodData,
};

try {
const existingLog = foodLogs.find((log) => log.meal_type === mealType);
if (existingLog) {
const response = await useUpdateFood(
uploadData,
existingLog.food_log_id
);
alert(response.message);
} else {
const response = await useInsertFood(uploadData);
alert(response.message);
}
await fetchFoodLogs(); // 데이터 업데이트 후 다시 불러오기
} catch (error) {
console.error('음식 데이터 업로드 중 오류 발생:', error);
}
};

return {
foodId,
logId,
dateId,
foodLogs,
mealTypes,
kcal,
handleFoodUpload,
};
};

export default useFood;

0 comments on commit bbb2929

Please sign in to comment.