TIL 33일차 ( 세션스토리지 모듈 분리 / getAuthUser 코드 수정)

KHW·2021년 10월 28일
0

TIL

목록 보기
36/39

세션스토리지 모듈 분리

API_END_POINT url은 생략

기존코드

  • src/api/GetAuthUser.js
import axios from 'axios'

const API_END_POINT = 'http://'

export default async function GetAuthUser(articleDataUrl) {
  const BearerToken = `Bearer ${sessionStorage
    .getItem('userInformation')
    .replace(/\"/gi, '')}`

  return await axios({
    method: 'get',
    url: `${API_END_POINT}/auth-user`,
    headers: {
      Authorization: BearerToken,
    },
    body: {
      isCover: false,
      image: articleDataUrl,
    },
  })
    .then((response) => response.data)
    .then(({ image }) => {
      return image
    })
    .catch((error) => {
      console.log(error)``
    })
}

sessionStorage가 안에서 존재한다.

수정코드

  • src/api/GetAuthUser.js
import axios from 'axios'
import { getItem_UserInformation } from '@SessionStorage'
const API_END_POINT = 'http://'

export default async function GetAuthUser(articleDataUrl) {
  const BearerToken = `Bearer ${getItem_UserInformation('userInformation')}`

  return await axios({
    method: 'get',
    url: `${API_END_POINT}/auth-user`,
    headers: {
      Authorization: BearerToken,
    },
    body: {
      isCover: false,
      image: articleDataUrl,
    },
  })
    .then((response) => response.data)
    .then(({ image }) => {
      return image
    })
    .catch((error) => {
      console.log(error)
    })
}
  • src/SessionStorage/index.js
export const getItem_UserInformation = (target) => {
  const userInformationStorage = sessionStorage.getItem(target)
  return userInformationStorage
    ? userInformationStorage.replace(/\"/gi, '')
    : undefined
}

export const setItem_UserInformation = (target, response) => {
  sessionStorage.setItem(target, JSON.stringify(response.data.token))
}

export const removeItem_UserInformation = (target) => {
  sessionStorage.setItem(target)
}

SessionStorage 폴더로 처리하여 분리하였고
target은 key로써 원하는 target 값에 따르는 값을 setItem하거나 removeItem하거나 getItem 할 수 있다.

sessionStorage 코드

Error 발생 X

sessionStorage.getItem('111')			//null

만약 없는 key값을 받아오려한다면 null 값으로 처리한다.
이때는 에러가 발생하지는 않는다.

Error 발생 O

sessionStorage.getItem('111').replace(/\"/gi, '')
//VM255:1 Uncaught TypeError: Cannot read properties of null (reading 'replace')
//    at <anonymous>:1:30

만약 없는 null 값을 replace를 사용하려하면 에러가 발생한다.

Error 발생하지않게 다루기

const userInformationStorage = sessionStorage.getItem('111')
  return userInformationStorage
    ? userInformationStorage.replace(/\"/gi, '')
    : undefined

만약 받아온 대상이 null일 경우 undefined를 리턴하게 처리해주고
null이 아닐경우 replace를 동작시켜 리턴시키게 하여
null일때 replace를 동작시키는 경우의 에러를 막는다.

getAuthUser 리팩토링하기

기존 코드

  • src/api/GetAuthUser.js
import axios from 'axios'
import { getItem } from '@SessionStorage'
const API_END_POINT = 'http://-'
export default async function GetAuthUser(articleDataUrl) {
  const BearerToken = `Bearer ${getItem('userInformation')}`
  return await axios({
    method: 'get',
    url: `${API_END_POINT}/auth-user`,
    headers: {
      Authorization: BearerToken,
    }
  })
    .then((response) => response.data)
    .then(({ image }) => {
      return image
    })
    .catch((error) => {
      console.log(error)
    })
}
  • src/components/MyInformation/index.js

....

const articleData = await GetAuthUser()
      setimageGetProps(articleData)

기존코드의 문제점

GetAuthUser의 의도인 data를 전부 다룰수있게 해야하는데 단지 image만 받아와 반환을 처리한다.
이러면 나중에 data의 다른 속성을 처리할 수 없다. (다형성이 없는느낌?)

수정코드

  • src/api/GetAuthUser.js
import axios from 'axios'
import { getItem } from '@SessionStorage'
const API_END_POINT = 'http://13.209.30.200'
export default async function GetAuthUser(articleDataUrl) {
  const BearerToken = `Bearer ${getItem('userInformation')}`
  return await axios({
    method: 'get',
    url: `${API_END_POINT}/auth-user`,
    headers: {
      Authorization: BearerToken,
    },
  })
    .then((response) => response.data)
    .then((data) => {
      return data
    })
    .catch((error) => {
      console.log(error)
  • src/components/MyInformation/index.js
const { image } = await GetAuthUser()
      setimageGetProps(image)

수정코드 결과

기존 data의 image속성값만 리턴에 비해 data를 리턴하여
필요한 부분에서 const { image } = await GetAuthUser() 분리하여 필요한 부분만 사용할 수 있다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글