삽질: axios , 삼항연산자, 두개이상의 경우의 수

웹 개발/Problems 2021. 6. 2. 20:19
import React, { useState, useEffect } from 'react';
import img from 'react';
import { Container } from './UserInfoMatchingDetailStyled.jsx';
const axios = require('axios');
const MatchingDetail = ({ participant }) => {
	let [userData, setUserData] = useState(null);
	let [tier, setTier] = useState('');
	let [kda, setKda] = useState(0);
	let [rank, setRank] = useState('');
	let [isLoading, setIsLoading] = useState(null);
	console.log('participant before useEffect: ', participant);
	useEffect(() => {
		console.log('participant: ');
		console.log(participant);
		if (participant) {
			setIsLoading(true);
			console.log('participant name: ');
			console.log(participant.summonerName);
			axios
				.get(
					`${
						process.env.REACT_APP_SERVER_URL
					}/utils/history?name=${'미키주일'}`,
				)
				.then((response) => {
					let data = response.data;
					let tempKda = 0;
					console.log('data: ');
					console.log(data);
					setTier(
						data.league_solo === undefined ? 'UNRANKED' : data.league_solo.tier,
					);
					setRank(data.league_solo === undefined ? '' : data.league_solo.rank);
					if (data.matches) {
						data.matches.forEach((match) => {
							tempKda += match.kda;
						});
						tempKda = tempKda / data.matches.length;
						console.log('tempKda before Math.floor: ');
						console.log(tempKda);
						tempKda = Math.floor(tempKda * 100) / 100;
						console.log('tempKda after Math.floor: ', tempKda);
						setKda(tempKda);
					}
					setIsLoading(false);
					setUserData(data);
				})
				.catch((err) => {
					console.log(err);
					setIsLoading(false);
				});
		}
	}, [participant]);
	// useEffect(() => {
	// 	if (userData.league_solo) {
	// 		console.log(userData);
	// 		setTier(userData.league_solo.tier);
	// 	}
	// }, [userData]);
	switch (isLoading) {
		case null: {
			return '';
		}
		case true: {
			return (
				<Container>
					<fieldset>
						{participant !== null ? <div>{participant.summonerName}</div> : ''}
						{'Loading...'}
						<button
							onClick={() => {
								setIsLoading(null);
							}}
						>
							close
						</button>
					</fieldset>
				</Container>
			);
		}
		case false: {
			return (
				<Container>
					<fieldset>
						{participant !== null ? <div>{participant.summonerName}</div> : ''}
						<div>
							<img
								src={require(`../../Images/tierIcons/${tier}.png`).default}
								width={'100'}
								height={'100'}
							/>
							{tier}
							{'   '}
							{rank}
							<div>{kda !== 0 ? kda : ''}</div>
						</div>
						<button
							onClick={() => {
								setIsLoading(null);
							}}
						>
							close
						</button>
					</fieldset>
				</Container>
			);
		}
	}
};

export default MatchingDetail;

participant 변수가 들어오면 axios를 실행해 그 지연시간동안 loading...을 보여줘야했다.

로딩인지 아닌지 확인하기 위해 isLoading 상태를 설정해주었지만 participant 변수가 들어오는 순간에는 isLoading이 기본값인 false로 인식되서 reference 에러가 났다. 생각을 해보니 이것은 세가지의 경우의수가 있는 문제라서 삼항연산자로 해결을 하기 매우 어렵다고 판단해 swtich문을 써서 리턴을 각각 다르게 했다.

경우 1. participant가 안들어 온 경우

경우 2. participant는 들어왔지만 아직 로딩이 안된 경우

경우 3. participant도 들어 오고 로딩이 끝나 데이터가 들어온 경우

따라서 삼항연산자로는 힘들다. 왜냐하면 경우 2번에서 participant가 들어오는 순간에는 로딩 변수의 기본값이 false인데, axios 실행전 setIsLoading(true)를 실행하지만 그것을 실행하기 전에 이미 false로 인식이 되어 로딩이 끝난줄 알고 데이터를 뿌릴려고 했다. 리액트에서 경우가 많아질 때 절대로 삼항 연산자는 피해야 겠다.

: