React, Axios
2024. 12. 23. 12:04ㆍ웹 개발
기본사용법
const onClick = async () => { // async
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); // await
setData(response.data);
} catch (error) {
console.log(error);
}
}
App.jsx
import './App.css'
import { useState } from 'react';
import styled from 'styled-components';
import axios from 'axios';
const StyledTextarea = styled.textarea`
width: 100%;
max-width: 400px;
`;
const App = () => {
const [data, setData] = useState(null);
const onClick = async () => { // async
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); // await
setData(response.data);
} catch (error) {
console.log(error);
}
}
return (
<div>
<div>
<button onClick={onClick}>불러오기</button>
</div>
{data && <StyledTextarea rows={7} value={JSON.stringify(data, null, 2)} readOnly={true} />}
</div>
)
};
export default App;
https://stackblitz.com/edit/vitejs-vite-sk6bnbp1?embed=1&file=src%2FApp.jsx
'웹 개발' 카테고리의 다른 글
React, Context + Consumer (0) | 2024.12.26 |
---|---|
React, usePromise 커스텀 훅 (0) | 2024.12.23 |
Javascript, Async / Await (2) | 2024.12.20 |
React Router DOM (1) | 2024.12.20 |
React Immer (0) | 2024.12.19 |