iT邦幫忙

2022 iThome 鐵人賽

DAY 28
0
Modern Web

30天學習Tauri系列 第 28

28.實作Tauri Todo - 完善Tauri

  • 分享至 

  • xImage
  •  

我們今天來改進我們的Todo App

新增todo\src\utils\store.tsx
https://ithelp.ithome.com.tw/upload/images/20221013/20108931oQuqrO08t0.png

import React, { createContext, useReducer, Dispatch } from 'react';

export interface ITodo {
  id: number,
  title: string,
  date: string,
  done: boolean
};

interface defaultState {
  todos: ITodo[];
};

const initState: defaultState = {
  todos: [],
};

export enum TodosActionType {
  TodosAddItem,
  TodosRemoveItem,
  TodosFetchAllItem
}

interface TodosAddItem {
  type: TodosActionType.TodosAddItem;
  payload: ITodo;
}

interface TodosRemoveItem {
  type: TodosActionType.TodosRemoveItem;
  payload: ITodo;
}

interface TodosFetchAllItem {
  type: TodosActionType.TodosFetchAllItem;
  payload: ITodo[];
}

type TodosActions = TodosAddItem | TodosRemoveItem | TodosFetchAllItem;


export const StoreCtx = createContext<{
  state: defaultState;
  dispatch: React.Dispatch<TodosActions>;
}>({
  state: initState,
  dispatch: () => undefined,
});

const reducer = (state: defaultState, action: TodosActions): defaultState => {
  switch (action.type) {
    case TodosActionType.TodosAddItem: {
      
    }
    case TodosActionType.TodosRemoveItem: {
      
    }
    case TodosActionType.TodosFetchAllItem: {
      
    }
    default:
      return state;
  }
};


interface Props {
  children: React.ReactNode;
}

export const StoreProvider: React.FC<Props> = ({children}) => {
  const [state, dispatch] = useReducer(reducer, initState);
  return (
    <StoreCtx.Provider value={{ state, dispatch }}>
      {children}
    </StoreCtx.Provider>
  );
}

將Provider加入todo\src\pages\_app.tsx

import type { AppProps } from "next/app";

import "../style.css";
import "../App.css";
import { StoreProvider } from "../utils/store";

// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <StoreProvider>
      <Component {...pageProps} />
    </StoreProvider>
  );
}

todo\src\pages\index.tsx加入

function App() {
  const { state, dispatch } = useContext(StoreCtx); // Add
  const { todos } = state;

上一篇
27.實作Tauri Todo - 從API上獲取天氣資訊
下一篇
29.實作Tauri Todo - 構建及發布
系列文
30天學習Tauri30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言