-
글쓴이글
-
2021년 12월 1일 00:05 #20969
MidNight참가자파이어베이스 이미지 올리는 것 까지 구현했는데 이미지를 안올리고 글만 작성했을시 undifined 라고 나옵니다.
Uncaught TypeError: Cannot read properties of undefined (reading 'name') 이런 에러로그가 나오는데
이미지 값을 안넣어서 그런것 같은데 안 넣어도 작동되게 할수있는 방법이 있을까요
2021년 12월 1일 00:13 #20970
MidNight참가자$("#send").click(function(){
var file = document.querySelector("#image").files[0];
var storageRef = storage.ref();
var 저장할경로 = storageRef.child('image/' + file.name);
var 업로드작업 = 저장할경로.put(file)업로드작업.on( 'state_changed',
// 변화시 동작하는 함수
null,
//에러시 동작하는 함수
(error) => {
console.error('실패사유는', error);
},
// 성공시 동작하는 함수
() => {
업로드작업.snapshot.ref.getDownloadURL().then((url) => {
console.log('업로드된 경로는', url);
const today = new Date();
const newtoday = today.toLocaleString()
var 저장할거 = {
제목: $("#title").val(),
가격: $("#price").val(),
내용: $("#content").val(),
날짜: newtoday,
이미지: url,
// uid: JSON.parse(localStorage.getItem("user")).uid,
// 이름: JSON.parse(localStorage.getItem("user")).displayName,
}db.collection("product").add(저장할거).then((result) => {
// window.location.href = '/index.html'
console.log(result);
}).catch((err) => {
console.log(err)
})
});여기서 if 구문을 써야할 꺼 같은데 image가 비어있을때와 있을때 두가지로넣어줘야할것같은데 잘모르겠습니다.
2021년 12월 1일 00:31 #20971
MidNight참가자if 구문으로 해결했습니다. 코드는
$("#send").click(function(){
var file = document.querySelector("#image").files[0];
if(file != null){
var storageRef = storage.ref();
var 저장할경로 = storageRef.child('image/' + file.name);
var 업로드작업 = 저장할경로.put(file)업로드작업.on('state_changed',
// 변화시 동작하는 함수
null,
//에러시 동작하는 함수
(error) => {
console.error('실패사유는', error);
},
// 성공시 동작하는 함수
() => {
업로드작업.snapshot.ref.getDownloadURL().then((url) => {
console.log('업로드된 경로는', url);
const today = new Date();
const newtoday = today.toLocaleString()
var 저장할거 = {
제목: $("#title").val(),
가격: $("#price").val(),
내용: $("#content").val(),
날짜: newtoday,
이미지: url,
// uid: JSON.parse(localStorage.getItem("user")).uid,
// 이름: JSON.parse(localStorage.getItem("user")).displayName,
}db.collection("product").add(저장할거).then((result) => {
// window.location.href = '/index.html'
console.log(result);
}).catch((err) => {
console.log(err)
})
});
}
);
}else{
const today = new Date();
const newtoday = today.toLocaleString()
var 저장할거 = {
제목: $("#title").val(),
가격: $("#price").val(),
내용: $("#content").val(),
날짜: newtoday// uid: JSON.parse(localStorage.getItem("user")).uid,
// 이름: JSON.parse(localStorage.getItem("user")).displayName,
}db.collection("product").add(저장할거).then((result) => {
// window.location.href = '/index.html'
console.log(result);
}).catch((err) => {
console.log(err)
})
}
});
이렇게 썼는데 작동은 됩니다. 그런데 이렇게 하는게 효율적인 코드일까요? 다른방법도 존재한다면 궁금합니다.
2021년 12월 1일 09:50 #20983
codingapple키 마스터경우에 따라서 분기를 주고 싶으면 if문밖에 없습니다
중복되는것 같은 코드들은 나중에 함수로 묶을 수도 있습니다
-
글쓴이글
- 답변은 로그인 후 가능합니다.