Tạo ứng dụng Todo với Redux có tương tác API trong Reactnative - P3

d52bb1 2024

Tiếp theo bài này, ít nhất bạn cần thực hiện thành công ví dụ mẫu ở phần 1: https://zezo.dev/view/tao-ung-dung-todo-voi-redux-co-tuong-tac-api-trong-reactnative-p1

 

Trong phần này sẽ thực hiện xây dựng chức năng Thêm mới

 

Bước 1: Chỉnh sửa Reducer thêm thao tác xử lý THÊM

Bên trong hàm builder của extraReducers, bạn thêm đoạn code xử lý kết Thêm addTodoAPI.fulfilled

 

builder.addCase(addTodoAPI.fulfilled, (state, action)=>{
              state.listTodo.push(action.payload);
          })
 		.addCase(addTodoAPI.rejected, (state, action) => {
            // Xử lý khi yêu cầu thêm todo bị từ chối hoặc xảy ra lỗi
            console.log('Add todo rejected:', action.error.message);
});

 

Bước 2: Tạo hàm addTodoAPI cho todoAction.js

Bạn vào file todoAction.js thêm hàm addTodoAPI như dưới đây. Chuỗi 'todo/addTodoAPI' là định danh xác định tên action.
 

export const addTodoAPI = createAsyncThunk(
    'todo/addTodoAPI',
    async (objTodo, thunkAPI) => {
      console.log(objTodo);
      try {
        // Gửi yêu cầu DELETE đến API để xóa todo
        const response = await fetch(api_url, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(objTodo)
        });
        const data = await response.json();
        // console.log(response);
        // Kiểm tra nếu status code là 200 hoặc 204 thì xóa thành công
        if (response.ok) {
            // console.log(response);
          // Sau khi xóa thành công, trả về id của todo đã xóa để cập nhật store
           return data; 
        } else {
          // Nếu có lỗi từ phía server, trả về lỗi
          const errorData = await response.json();
          return thunkAPI.rejectWithValue(errorData);
        }
      } catch (error) {
        // Xử lý lỗi nếu có bất kỳ lỗi nào xảy ra
        return thunkAPI.rejectWithValue(error.message);
      }
    }
  );

Bước 3: Chỉnh sửa todoScreen.js để hiển thị chức năng THÊM

 Trước lệnh return của component TodoScreen, bạn thêm hàm xử lý THÊM như sau:

//Khai báo  state để thực hiện thêm
    const [title, setTitle] = useState('');
    
// hàm xử lý việc thêm
    const handleAddTodo = ()=>{
        let duLieuThem = {  title: title , status: false};
        // dispatch( addTodo ( duLieuThem )  );
        dispatch(addTodoAPI(duLieuThem))
        .then((result) => {
            // console.log(result);
            console.log('Todo add successfully!');
        })
        .catch((error) => {
            console.error('Error add todo:', error);
        });
    }

 Trong phần return view bạn thêm ô nhập text và nút bấm thêm

 

<TextInput placeholder="Nhập công việc" onChangeText={setTitle} />
<View style={{width:100}}>
    <Button title="Thêm việc" onPress={handleAddTodo} />
</View>

Không quên import thêm component nhé

import {  Text, View ,TouchableOpacity,TextInput,Button} from "react-native";

import { fetchTodos, deleteTodoApi, addTodoAPI} from '../redux/actions/todoAction';

 

Bạn chạy lại ứng dụng để thử nghiệm kết quả

 

Nguồn: zezo.dev