개발 일기
Redux thunk 글쓰기, 삭제, 완료 본문
axios란?
- 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
- Promise(ES6) API 사용
- 요청과 응답 데이터의 변형
- HTTP 요청 취소
- HTTP 요청과 응답을 JSON 형태로 자동 변경
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
// 0. 값 조회
export const __getTodos = createAsyncThunk(
"GET_TODOS",
async (arg, thunkAPI) => {
try {
// 무조건!
const todos = await axios.get("http://localhost:3001/todos");
// console.log("todos.data", todos.data);
return thunkAPI.fulfillWithValue(todos.data);
} catch (err) {
// 만약 오류가 나면 여기!
return thunkAPI.rejectWithValue(err);
}
}
);
// 1. 추가
export const __addTodoThunk = createAsyncThunk(
"ADD_TODO",
async (arg, thunkAPI) => {
try {
// 시도할 내용
const response = await axios.post("http://localhost:3001/todos", arg);
// console.log("response", response);
return thunkAPI.fulfillWithValue(response.data);
// return thunkAPI.fulfillWithValue(arg);
} catch (err) {
// 오류가 났을 때의 내용
console.log(err);
return thunkAPI.rejectWithValue(err);
}
}
);
export const __deleteTodoThunk = createAsyncThunk(
"DELETE_TODO",
async (arg, thunkAPI) => {
try {
await axios.delete(`http://localhost:3001/todos/${arg}`);
return thunkAPI.fulfillWithValue(arg);
} catch (error) {
return console.log(error);
}
}
);
export const __switchTodoThunk = createAsyncThunk(
"SWITCH_TODO",
async (arg, thunkAPI) => {
try {
axios.patch(`http://localhost:3001/todos/${arg.id}`, arg);
return thunkAPI.fulfillWithValue(arg);
} catch (e) {
return thunkAPI.rejectWithValue(e);
}
}
);
// initial states
const initialState = {
todos: [],
isSuccess: false,
isLoading: false,
error: null,
};
// createSlice의 결과물 -> action creators와 reducers
const todosSlice = createSlice({
name: "todos",
initialState,
extraReducers: {
[__getTodos.fulfilled]: (state, action) => {
state.todos = action.payload;
},
[__addTodoThunk.fulfilled]: (state, action) => {
state.todos.push(action.payload);
},
[__deleteTodoThunk.fulfilled]: (state, action) => {
state.todos = state.todos.filter((item) => item.id !== action.payload);
},
[__switchTodoThunk.fulfilled]: (state, action) => {
state.todos = state.todos.map((item) => {
if (item.id === action.payload.id) {
return { ...item, isDone: !item.isDone };
}
return item;
});
},
},
});
export const { removeTodo, switchTodo } = todosSlice.actions;
export default todosSlice.reducer;
axios를 활용한 추가, 삭제, 완료를 구현해봤다.
axios에는 GET, POST, PUT, DELETE가 있는데 나는 그중 GET, POST, DELETE를 사용했다.
PUT은 저장된 내용을 갱신하는 목적으로 사용하는데 PUT도 한번 써봐야 겠다.
프로젝트에서도 계속 firebase를 사용했는데 axios를 처음 공부해보니 axios가 더 사용이 생각보다 간편하고 쉽다고 느껴졌다.
axios를 사용하기 전에 우선
npm install -g json-server
json-server를 설치 후에 db.json을 생성후
json-server --watch ./db.json --port (원하는 숫자 ex)3001)
이렇게 서버를 열어주면 된다.
오늘은 공부를 위해 TodoList에 적용해 봤는데 처음부터의 과정을 통해 게시판을 만들어봐야겠다.
반응형
'개발 일기' 카테고리의 다른 글
한주의 회고록 (0) | 2023.02.06 |
---|---|
동적 웹과 정적 웹(동기, 비동기) (0) | 2023.01.31 |
한주의 정리 (0) | 2023.01.30 |
firebase useState를 이용한 수정 관리 (0) | 2023.01.27 |
React 모달 구현하기 (외부 클릭 닫기) (0) | 2023.01.26 |