React의 useEffect () 후크에 비동기 함수 넣기

Oct 04 2020

보안 API 뒤에 GoogleMap API 키를 숨기고 싶은 앱을 마무리하고 있습니다. 내 의도는 인증 된 사용자가 있음을 확인한 후 API 키를 호출하는 것입니다. 문제는 비동기 호출 사이에 변경 사항이 상태 변경에 반영되지 않는다는 것입니다.

이것이 내가하는 일입니다.

export default function App() {
  const [dateRange, setDateRange] = useState(initialDateRange);
  const [formState, updateFormState] = useState(initialFormState);
  const [user, setUser] = useState(null);
  const [googleApiKey, setGoogleApiKey] = useState(null);

  useEffect(() => {
    async function updateAuth() {
      try {
        await checkUser();
        await getGoogleApiKey();
        await setAuthListener();
      } catch (error) {}
    }
    updateAuth();
  }, []);

  async function checkUser() {
    try {
      const user = await Auth.currentAuthenticatedUser();
      setUser(user);
      if (user !== authenticatedUser) {
        updateFormState(() => ({
          ...formState,
          authenticatedUser: user
        }));
      }
    } catch (error) {
      console.log(error);
    }
  }

  async function getGoogleApiKey() {
    const googleApiUrl = `${process.env.REACT_APP_API_PATH}apikey?googleapikey=true`; 
    try {
      console.log('USER_USER_USER', user);
      const apiKey = await fetch(googleApiUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: user.signInUserSession.idToken.jwtToken
        }
      });
      console.log('GOT_GOOGLE_API_KEY', apiKey);
      setGoogleApiKey(apiKey);
    } catch (error) {
      console.log(error);
    }
  }

  async function setAuthListener() {
    Hub.listen('auth', (data) => {
      const event = data.payload.event;
      switch (data.payload.event) {
        case 'signOut':
          console.log('signing out...');
          console.log(event);
          updateFormState(() => ({
            ...formState,
            username: '',
            password: '',
            email: '',
            authenticatedUser: null
          }));
          break;
        default:
          break;
      }
    });
  }

하지만 오류가 발생합니다.

USER_USER_USER null
App.js:78 TypeError: Cannot read property 'signInUserSession' of null
    at getGoogleApiKey (App.js:72)
    at updateAuth (App.js:42)

이것이 잘못된 패러다임이라면 대안을 고맙게 생각합니다!

답변

4 Yuan-HaoChiang Oct 04 2020 at 08:33

때 setUser호출되면 user변수는 여전히 기존 보유 user(정보 null에 관계없이이 경우에는) async/await:

await checkUser();        // setUser(something) will not happen until next run
await getGoogleApiKey();  // user is still null
await setAuthListener();

다른 선택은 user변경 될 때 다른 효과를 추가하는 것입니다 .

useEffect(() => {
  if (user) {
     getGoogleApiKey();
  }
}, [user]);

또는 getGoogleApiKey매개 변수로 호출 하십시오.

const user = await checkUser(); // return user
await getGoogleApiKey(user);
await setAuthListener();

로직이 복잡해 지므로 디스패치가이 복잡한 앞뒤 시나리오를 단순화하기 때문에 useReducer 후크를 사용해 보는 것이 좋습니다 .