관리 메뉴

bright jazz music

1. React에서 axios 사용하기(GET) 본문

Framework/ReactJs

1. React에서 axios 사용하기(GET)

bright jazz music 2023. 5. 21. 19:24

 

https://swapi.dev/api/ 사이트에서 비동기로 배열을 가져와 보았다. 성공

https://swapi.dev/api/

일부러 잘못된 url을 기재하여 실패하게 하였다.

 

 

 

 

 

1. App.js 작성

import { useEffect, useState } from "react";
import axios from "axios";

function App() {

  const [people, setPeople] = useState([]);
  const [error, setError] = useState(null);
  const [ok,setOk] = useState(null);

  // 동기처리
  // useEffect(() => {
  //   axios.get('https://swapi.dev/api/people/')
  //     .then((data) => {
  //       console.log('##data', data)
  //       setPeople(data.data?.results)
  //       debugger
  //     })
  // }, [])


  //비동기 처리. 그러나 useEffect훅에서 async를 직접 사용할 수 없어 에러남
  // 그래서 아래와 같이 비동기 함수를 새로 생성해주고 useEffect에서 사용해줌.
  // useEffect( async () => {
  //   try{
  //     const data = await axios.get('https://swapi.dev/api/people/');
  //     setPeople(data.data?.results)
  //   }catch(e) {
  //     setError('Something went wrong');
  //   }
  // }, [])


  //이게 작동하는 코드
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://swapi.dev/api/people/');
        setPeople(response.data?.results);
        setOk('OK!')
      } catch (error) {
        setError('Something went wrong.');
      }
    };
  
    fetchData();
  }, []);

  return (
    <div className="App">
      {ok && <h3>{ok}</h3>}
      {error && <h3>{error}</h3>}

      App
      {/* {JSON.stringfy(people)} */}
      {people.length 
        ? (
          <>
            {people.map((person) => (
              <h1>{person.name}</h1>
            ))}
          </>)
          : <div>Loading ... </div>}
    </div>
  )
}

export default App;

 

2. 자바스크립트의 AND 연산자 표현

 

`{ok && <h3>{ok}</h3>}`는 JavaScript의 논리적 AND 연산자를 활용한 표현식이다. 
이 표현식은 `ok`라는 변수가 `true`로 평가될 때만 `<h3>{ok}</h3>`를 렌더링 한다. 

`ok`가 `true`로 평가되는 조건은 `ok`가 `null`, `undefined`, `false`, `0`, `NaN`이 아니라는 것입니다. 
따라서 `ok`가 어떤 값으로 설정되었을 때에만 `<h3>{ok}</h3>` 요소가 렌더링되며, 그 값은 `<h3>` 요소 안에 표시된다.

 

{error && <h3>{error}</h3>} 역시 마찬가지.

 

3. JSON.stringfy( )

 

4. TypeError: destroy is not a function

useEffect에서 비동기처리를 위한 async 함수를 직접 사용하려고 했기 때문에 발생한 에러이다.

async를 사용하는 별개의 함수를 선언하고 그것을 useEffect 훅에서 사용하면 해결된다.

TypeError: destroy is not a function

'Framework > ReactJs' 카테고리의 다른 글

3. React에서 axios 사용하기(POST) 테스트  (0) 2023.05.22
2. React에서 axios 사용하기(POST)  (0) 2023.05.21
생활코딩: next.js  (0) 2023.05.18
생활코딩: Redux toolkit  (0) 2023.05.17
생활코딩: react-redux 예제2  (0) 2023.05.17
Comments