Skip to content

Latest commit

 

History

History
92 lines (71 loc) · 3.27 KB

README.md

File metadata and controls

92 lines (71 loc) · 3.27 KB

WP React Typescript

A starter fully functional dashboard theme with Authentication using Wordpress API & React

About

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.

Demo

wp-react

https://wp-react-ts.lougiequisel.com/signin

React Redux Actions

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:

  1. Ask yourself if what are the data you need? On my end, I need a Post data specically these fields id, title, content, excerpt, modified & dateso 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;
}
  1. 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;
}
  1. 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.

React Redux Reducers

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.

Code completion and IntelliSense

When done right, you will have a very intelligent code suggestions upon typing in your Code Editor.

License

MIT