A starter fully functional dashboard theme with Authentication using Wordpress API & React
Based from this original project. wp-react-typescript
was developed to help other React.js developers in building an admin section of their project. They can make this their guide in integrating authentication using JWT. This will also help them properly type their React project especially when using react-redux
with Typescript.
https://wp-react-ts.lougiequisel.com/signin
I think the most complicated part of this project is to implement type checking for redux's Actions & Reducers. These are the steps that helped me typed those easily:
- Ask yourself if what are the data you need?
On my end, I need a
Post
data specically these fieldsid
,title
,content
,excerpt
,modified
&date
so my interface should look like this:
interface Rendered {
rendered: string;
}
export interface Post {
id: number;
title: Rendered;
content: Rendered;
excerpt: Rendered;
modified: string;
date: string;
}
- Create a secondary interface for the dispatch
type
&payload
properties. This will be very useful in creating our Actions so we have to export it as well.
export interface FetchPostAction {
type: ActionWPTypes.fetchPost;
payload: Post;
}
- Implement the interfaces to your actions.
export const fetchPosts = () => {
return async (dispatch: Dispatch) => {
try {
const response = await axios.get<Post[]>(`${Constants.apiUri}/posts`);
dispatch<FetchPostsAction>({
type: ActionWPTypes.fetchPosts,
payload: response.data
});
dispatch<ClearMessageAction>({ type: ActionMessagesTypes.clearMsg });
} catch (error) {
console.log(error);
}
};
};
Please see the full code under /src/actions directory.
To implement type checking on your reducers. You just have to import all the Action's dispatch interfaces and make a Union type out of those. Your action should look like this:
type Actions = FetchCurrentUserAction | FetchPostsAction | FetchPostAction | UpdatePostAction | PublishPostAction | DeletePostAction;
Please see the full code under /src/reducers directory.
When done right, you will have a very intelligent code suggestions upon typing in your Code Editor.
MIT