728x90
반응형
1. GET: 데이터 조회
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInpuValue] = useState({
//id : json의 방식의 데이터는 자동으로 입력됨
title: '',
});
//[조회]
const fetchTodos = async () => {
const { data } = await axios.get('http://localhost:4002/todos');
console.log('data', data);
setTodos(data);
};
useEffect(() => {
fetchTodos();
}, []);
return (
<div>
{/* 데이터 영역 */}
{todos?.map((item) => {
return (
<div key={item.id}>
{item.id} : {item.title}
</div>
);
})}
</div>
);
}
export default App;
▶ await axios.get('http://localhost:4002/todos');
2. POST : 데이터 추가
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInpuValue] = useState({
//id : json의 방식의 데이터는 자동으로 입력됨
title: '',
});
//변경사항
const [tartgetId, setTartgetId] = useState('');
const [tartgetContent, setTartgetContent] = useState('');
//[추가]
//async함수 : submit을 눌렀을때 post요청을 하니깐.
//인자값 필수 : 어떤 값을 보낼건지 (newTodo)--> 지금 코드에서는 필요없음.
const onSubmitHandler = async () => {
axios.post('http://localhost:4002/todos', inputValue);
//setTodos([...todos, inputValue]); //id값이 안나오는 부분을 개선하기위해 아래 조회함수를 다시 호출
fetchTodos();
};
useEffect(() => {
fetchTodos();
}, []);
return (
<>
<div>
{/* input 영역 */}
<form
onSubmit={(e) => {
e.preventDefault();
//버튼 클릭시, input에 들어있는 값 (state)를 이용해 DB에 저장 (post요청)
onSubmitHandler();
}}
>
<input
type="text"
value={inputValue.title}
onChange={(e) => {
setInpuValue({ title: e.target.value });
}}
></input>
<button>추가</button>
</form>
</div>
</>
);
}
export default App;
▶ axios.post('http://localhost:4002/todos', inputValue);
▼ Each child in a list should have a unique "key" prop.
[오류]
db에는 id값이 자동으로 입력되지만, state에는 값을 알수없어서 공란으로 나옴
=> 새로고침하면 잘 나옴 (db에 있으니깐)
[해결]
조회함수를 다시한번 호출하면 됨
const onSubmitHandler = async () => {
axios.post('http://localhost:4002/todos', inputValue);
//setTodos([...todos, inputValue]); //id값이 안나오는 부분을 개선하기위해 아래 조회함수를 다시 호출
fetchTodos();
};
3. DELET : 데이터 삭제
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInpuValue] = useState({
//id : json의 방식의 데이터는 자동으로 입력됨
title: '',
});
//[삭제]
//async함수 : 버튼 눌렀을때 post요청을 하니깐.
const onDeleteBtnHandler = async (id) => {
axios.delete(`http://localhost:4002/todos/${id}`);
setTodos(
todos.filter((item) => {
return item.id !== id;
})
);
};
useEffect(() => {
fetchTodos();
}, []);
return (
<div>
{/* 데이터 영역 */}
{todos?.map((item) => {
return (
<div key={item.id}>
{item.id} : {item.title}
{' '}
<button
onClick={() => {
onDeleteBtnHandler(item.id);
}}
>
삭제
</button>
</div>
);
})}
</div>
);
}
export default App;
▶ axios.delete(`http://localhost:4002/todos/${id}`);
▶ 삭제하고 데이터는 필터로 걸러서 보여주기
4. PATCH : 데이터 변경
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [todos, setTodos] = useState(null);
const [inputValue, setInpuValue] = useState({
//id : json의 방식의 데이터는 자동으로 입력됨
title: '',
});
//변경사항
const [tartgetId, setTartgetId] = useState('');
const [tartgetContent, setTartgetContent] = useState('');
//[변경]
//patch 사용
const onUpdateBtnHandler = () => {
axios.patch(`http://localhost:4002/todos/${tartgetId}`, {
title: tartgetContent,
});
setTodos(
todos.map((item) => {
if (item.id == tartgetId) {
return { ...item, title: tartgetContent };
} else {
return item;
}
})
);
};
useEffect(() => {
fetchTodos();
}, []);
return (
<>
<div>
{/*변경 영역*/}
<input
type="text"
value={tartgetId}
onChange={(e) => {
setTartgetId(e.target.value);
}}
placeholder="변경할 아이디"
></input>
<input
type="text"
value={tartgetContent}
onChange={(e) => {
setTartgetContent(e.target.value);
}}
placeholder="변경할 내용"
></input>
<button onClick={onUpdateBtnHandler}>변경</button>
<br />
<br />
</div>
);
}
export default App;
▶ axios.patch(`http://localhost:4002/todos/${tartgetId}`
▶변경하고 데이터는 map 메서드 사용해서 데이터 변경 & 그대로 보여주기
끝.
반응형
'React' 카테고리의 다른 글
리액트 : 로그인 & 회원가입 구현 (axios api 사용) (1) | 2023.12.01 |
---|---|
리액트 : 인증/인가(쿠키, 세션, 토큰, JWT) (0) | 2023.11.30 |
리액트 오류 : Too many re-renders. React limits the number of renders to prevent an infinite loop. (0) | 2023.11.29 |
[리액트 심화] 비동기통신 Axios interceptor (0) | 2023.11.28 |
리액트 오류 : A component is changing a controlled input to be uncontrolled. (0) | 2023.11.28 |