React - browser-image-compression

DONNIE·2022년 10월 24일
0

React

목록 보기
5/26

browser-image-compression

에로사항

  • 프로필 사진 업로드시 용량이 큰 파일은 처리되지 않음
  • 기존 로직에 이미지 압축을 추가함
  • optimistic updates로 화면단 업데이트는 되나 서버에 업로드는 2,3번 시도해야됨

해결방법

  • async, await으로 동기처리

API 통신

    useEffect(()=>{
        
        var formData = new FormData();
      
        formData.append('user_id',user);
        formData.append('file',compressedProfile)
        fetch(config.URL_ADDRESS+config.UPDATE_PROFILE, {
        method: 'PATCH',
        mode:'cors',
        headers: {
                'Accept':'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
                'Authorization': 'Bearer ' + accToken,
               },
        cache: 'no-cache',
        body: formData // body 부분에 폼데이터 변수를 할당
      })
      .then((response) => {

        if(response.ok) {
            setInfo({
                ...info,
                profile:URL.createObjectURL(profileFile)
            })
            
        }
       
      })
      .catch((e) => {
        console.log(e)
      })
    },[profileFile])

기존코드

    const onUpdateProfile= (e)=>{
        const uploadImg = e.target.files
        setProfileFile(...uploadImg)
        pressedimg(e.target.files)
    }

    async function pressedimg (files){
        let pressedImg = []
        console.log(files.length,'filesfilesfilesfiles')
        try {
            pressedImg = await imageCompression(files[0], {maxSizeMB: 2});
            setCompressedProfile(pressedImg)
            
        }catch (err) {
            console.log(err)
        }
    } 

버그 개선된 코드

    const onUpdateProfile=async (e)=>{
        const uploadImg = e.target.files
        await pressedimg(e.target.files) // 서버 통신이 지연되는 것으로 추정하고 awa
        setProfileFile(...uploadImg)
        
    }

    async function pressedimg (files){
        let pressedImg = []
        console.log(files.length,'filesfilesfilesfiles')
        try {
            pressedImg = await imageCompression(files[0], {maxSizeMB: 2});
            setCompressedProfile(pressedImg)
            
        }catch (err) {
            console.log(err)
        }
    } 

=> API 통신을 profileFile의 state 값에 따라 하므로 이미지 압축보다 해당 state값 업데이트가 먼저되면 이미지 압축전에 통신이 선행되어 프로필 이미지가 변경되지 않았음
=> 그래서 코드 순서 바꾸고 async / await 추가

profile
후론트엔드 개발자

0개의 댓글