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

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 Sửa

Bước 1: Chỉnh sửa Reducer thêm thao tác xử lý SỬA

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

 

builder.addCase(updateTodoApi.fulfilled, (state, action)=>{
            // lấy tham số truyền vào
            // console.log(action);
            const { id, title } = action.payload;
            // tìm bản ghi phù hợp với tham số truyền vào
            const todo = state.listTodo.find(row => row.id === id);
            // update
            if (todo ) {
                todo.title = title; // gán giá trị
            }
      })
      .addCase(updateTodoApi.rejected, (state, action) => {
            // Xử lý khi yêu cầu Sửa todo bị từ chối hoặc xảy ra lỗi
            console.log('Update todo rejected:', action.error.message);
});

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

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

 

export const updateTodoApi = createAsyncThunk(
  'todo/updateTodoApi',
  async (objUpdate, thunkAPI) => {
    // console.log('objupdate: '+ JSON.stringify(objUpdate));
     try {
      // Gửi yêu cầu DELETE đến API để xóa todo

      const response = await fetch(`${api_url}/${objUpdate.id}`, {
        method: 'PUT',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(objUpdate.data)
      });
      
      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 SỬA

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

  // Dành cho sửa: Cần có state lưu trạng thái đang sửa bản ghi nào
    const [editTitle, setEditTitle] = useState('');// chuỗi tiêu đề
    const [idEdit, setIdEdit] = useState(null); //lưu id bản ghi cần sửa
  
  const handleEdit = (id, title) =>{
        // hàm này để  ẩn hiện form sửa
        setEditTitle(title);
        setIdEdit(id);
    }
    // hàm lưu kết quả sửa
    const handleUpdate =()=>{ 

        let duLieuUpdate = {  title: editTitle};
        // dispatch( addTodo ( duLieuThem )  );

        dispatch(updateTodoApi({id: idEdit, data:duLieuUpdate}))
        .then((result) => {
            // console.log(result);

            console.log('Todo update successfully!');
            setEditTitle('');
            setIdEdit(null);
        })
        .catch((error) => {
            console.error('Error update todo:', error);
        });
    }

 Không quên import updateTodoApi ở Screen nhé.

 

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

 Xuống dưới phần return cải tiến code toàn bộ phần hàm map để chỉnh trình bày giao diện sửa

 

{
                listTodo.map(row =>(
                    <View key={row.id} 
                     style={{margin:10,padding:10, borderColor:'blue', borderWidth:1}}>
                      
                      {
                          (idEdit === row.id)?
                              (<>
                                  <TextInput
                                          value={editTitle}
                                          onChangeText={setEditTitle}
                                          onBlur={handleUpdate}
                                          autoFocus
                                      />
                                      <Button title="Update" onPress={handleUpdate} />
                              </>
                              )
                          :
                              (
                                  <>
                                    <Text>{row.title}  -  {row.id}</Text>
                                      <TouchableOpacity onPress={()=>handleDeleteTodo(row.id)} >
                                          <Text style={{color: 'red'}}>Xóa</Text>
                                      </TouchableOpacity> 
  
  
                                      <TouchableOpacity onPress={() => handleEdit(row.id, row.title)}>
                                          <Text>Edit</Text>
                                      </TouchableOpacity>
                                  </>
  
                              )
                      }
                      
                    </View>  
                  ))
           }

 Chạy lại ứng dụng để thử nghiệm thao tác sửa.

 

Nguồn: zezo.dev