I seem to be a bit confused about how I should be utilizing thunk in my code. Initially, I thought I could use it to dispatch async actions like the example below:
app/index.ts
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducers/index";
const store = createStore(reducer, {}, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root") as HTMLElement,
);
actions.ts
export interface RemoveDoneAction {
type: TypeKeys.REMOVE_DONE;
done: Task;
}
export const removeDone: ThunkAction<Promise<void>, Task, {}> =
(dispatch, getState) => {
const done = getState();
return done.delete() // Call API
.then(() => { // Send Action
const action: RemoveDoneAction = {
type: TypeKeys.REMOVE_DONE,
done,
};
dispatch(action);
});
};
todo.tsx
import * as React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { removeDone } from "./actions";
interface IDoneProps {
doneList: Task[];
dispatch: Dispatch<{}>;
}
class Done extends React.Component<IDoneProps, {}> {
public removeFromDone = (index: number) => {
const todo = this.props.doneList[index];
//call thunk action!
removeDone(this.props.dispatch, () => (todo), {}).then(() => {
console.log("thunk then!");
});
}
public render() {
//create a item from each done
const doneItems = this.props.doneList.map((done, i) => {
return (
<TodoItem
text={done.description}
key={i}
index={i}
icon="close"
iconColor="#d67866"
onClick={this.removeFromDone}
/>
);
});
return (
<Card title={`${this.props.doneList.length} todo${this.props.doneList.length > 1 ? "s" : ""} done`}>
<ul>
{doneItems}
</ul>
</Card>);
}
}
export default connect((state) => {
return { doneList: state.done };
})(Done);
Even though this approach is functional, I have realized that I'm passing the context into the state and not passing anything into extraArgs...
I'm struggling to comprehend why thunk would require access to the state given that it's simply dispatching actions to the reducers?!
I have a feeling I might be overlooking something...