I'd like to keep track of API requests that I make with react-redux. To do this I'd like to generate a request Id inside the action and pass that along to middleware and reducers through the payload. Then when I'm dispatching the action from my component I can capture the request Id and use it for updating the component as the request progresses.
Here's some example code
State
export interface State {
[requestId: number]: Request;
}
export interface Request {
status: string;
error?: string;
}
Action
export function createRequest(): Action {
return {
type: "request",
payload: {
requestId: Math.random () // Make a random Id here
}
};
}
Reducer
export function createRequestReducer(state: State): State {
return {
...state,
...{ state.payload.requestId: { status: "pending" } }
};
}
Component
interface props {
getRequestById: (id: number) => Request;
createRequest: () => number;
}
const component = (props: testProps): JSX.Element => {
const getRequestById = props.getRequestById;
const [requestId, setRequestId] = useState(null);
const [request, setRequest] = useState(null);
useEffect(() => {
if (requestId !== null) {
setRequest(getRequestById(requestId));
}
}, [requestId]);
return <div>The request status is {(request && request.status) || "Not started"}</div>;
}
function mapStateToProps(state: State) {
return {
getRequestById: (requestId: number): Request => {
getRequestById(state, requestId)
}
};
}
function mapDispatchToProps(dispatch: Dispatch) {
return {
createRequest: (): number => {
const action = createRequest();
dispatch(action);
return action.payload.requestId;
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(component);
I expect this will work but it may be a massive anti pattern. Is this not advised and, if so, is there an alternative?