아하 로고
검색 이미지
생활꿀팁 이미지
생활꿀팁생활
생활꿀팁 이미지
생활꿀팁생활
기특한관박쥐161
기특한관박쥐16121.02.21

리액트에서 REST API 요청할 때는 쓰는 구문

바닐라 형태의 JS가 아니라,

리액트에서 서버로 API를 요청할 때 주로 어떤 코드를 사용하나요?

제가 알고 있는 것은 일반적으로,

const xhr = new XMLhttpRquest();

위 코드처럼 xhr 객체를 만들어서 요청하고 응답에 대한 에러코드 짜는 것으로 알고 있는데

리액트에서 작동은 하겠지만, 리액트에서도 주로 이렇게 사용하나요?

55글자 더 채워주세요.
답변의 개수1개의 답변이 있어요!
  • 안녕하세요 현직 웹 개발자입니다.

    React 에서는 주로 axios 라는 라이브러리를 사용하여 REST API 를 호출합니다.

    그 외에도 다른 방법들도 있으며, 많은 방법중 하나라고 생각하시면 됩니다. 효율적으로 react 의 state 를 다루기 위해서 redux 를 사용한뒤 redux-saga, redux-thunk 등의 middleware 를 연동하여 api 를 호출하는 경우가 있지만, 난이도가 있어서 react 를 처음 사용하시는 분들께 알려드리면 대부분 너무 어려워 하십니다. redux 를 배우신뒤 redux 에서 async action을 이용하여 api 를 호출하시는 방법을 배우시는것을 추천드립니다.

    우선 class component 에서 axios 를 사용하는 예제입니다.

    (링크: https://codesandbox.io/s/jv73ynwz05?file=/src/index.js)

    import { render } from 'react-dom'; import React, { Component } from 'react'; import axios from 'axios' class App extends Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { axios.get('https://randomuser.me/api/?results=50') .then(response => { const data = response.data.results; this.setState({ data }) }) .catch(error => { console.log(error); }) } render() { return ( <div className="App"> {this.state.data.map((item, index) => <UserList key={index} {...item} />)} </div> ); } } const UserList = (props) => ( <p><strong>name : </strong> {props.name.first}</p> ) render(<App />, document.getElementById('root'));

    위의 예제와 같이 componentDidMount 에서 axios 를 호출하는 경우 페이지가 mount 된경우 (불러와서 화면에 보일때), 호출이 됩니다. 바닐라 JS 의 onload 인 경우와 비슷합니다. 하지만 class component 는 react 에 hook 이 소개된 이후로 저같은 경우 사용한 적이 없습니다.

    다음은 functional component 에서 axios 를 사용하는 경우, use-axios-react 라는 라이브러리를 사용하여 좀더 효율적으로 API 를 호출할 수 있습니다. 먼저 POST 예제입니다.

    (링크: https://codesandbox.io/s/8x59c?file=/src/index.js)

    import React from "react"; import ReactDOM from "react-dom"; import { usePostCallback } from "use-axios-react"; function userToRequest({ name, job }) { return { url: "https://reqres.in/api/users", data: { name, job } }; } const CreateUser = () => { const [create, sending, { error, data }] = usePostCallback(userToRequest); const neo = { name: "Neo", job: "The One" }; const morpheus = { name: "Morpheus", job: "Leader" }; return ( <Layout> <Button onClick={() => create(neo)}>Neo</Button> <Button onClick={() => create(morpheus)}>Morpheus</Button> <StatusBar sending={sending} error={error} lastUser={data} /> </Layout> ); }; const Layout = ({ children }) => ( <div className="p-5"> <h1 className="mb-5">Create sample users:</h1> {children} </div> ); const Button = ({ onClick, children }) => ( <button onClick={onClick} className="btn btn-primary mr-2"> {children} </button> ); const StatusBar = ({ sending, error, lastUser }) => ( <div className="mt-5"> {sending && <div>Sending...</div>} {error && <code>{JSON.stringify(error)}</code>} {!sending && lastUser && <code>{JSON.stringify(lastUser)}</code>} </div> ); ReactDOM.render(<CreateUser />, document.getElementById("root"));

    그리고 GET 예제입니다.

    (링크: https://codesandbox.io/s/hlmb2?file=/src/index.js)

    import React from "react"; import ReactDOM from "react-dom"; import { useGetData } from "use-axios-react"; const KanyeQuote = () => { const [data, loading] = useGetData("https://api.kanye.rest/"); if (loading) return <div>Loading...</div>; return <blockquote>{data.quote}</blockquote>; }; const App = () => ( <div style={{ padding: "5%" }}> <h1 className="mb-5">Kanye says</h1> <hr /> <div className="my-5"> <KanyeQuote /> </div> </div> ); ReactDOM.render(<App />, document.getElementById("root"));

    그럼 도움이 되셨길 바랍니다.

    수고하세요.