Redux setup
The Starter Kit uses Redux for state management. Althought the React Context API has gained a lot of popularity recently, Redux is still the better option for larger applications where state changes more frequently.
All Redux files live in the /client/store
directory.
API calls
ALL calls to the Laravel backend API are conducted via Redux. NO component within the /client/pages
directory makes API calls directly but invoke them via dispatching the respective action in Redux.
store.tsx
As larger applications might need different reducers (e.g., one for users, one for blog posts etc.), the store.tsx
is responsible for combining all other reducers (in the store
variable) that live in the store
directory (more on that later). store.tsx
is also responsible for initializing the Redux devtools so you can debug your application better. The store
variable holds all the reducers and gets passed as the Provider store in /client/pages/_app.tsx
.
actionTypes.tsx
This file exports constant variable names that are referenced when dispatching actions. You can also use strings directly in your reducer or action files, but you then increase the risk of spelling errors and the alike.
Reducers
As mentioned above, the app allows you to easily create multiple reducers. Look, for example, at /client/store/auth
. The authStore.tsx
holds the user store, while the authActions.tsx
uses the redux-thunk
middleware to dispatch actions asynchronously.
Actions
By default, Redux does not allow us to asynchronously dispatch actions. This can only be achieved by using the redux thunk
middleware. As we do all our API calls in Redux we take heavy use of that package.
We conduct all our dispatches in storeName/${storeName}Actions.tsx
files.
Take a look at /client/store/auth/authActions.tsx
, for example. Each method itself is not declared as asynchronous, but they return async
functions.
Example:
export const loadUser = () => {
return async (dispatch: CallableFunction) => {
// To someting...
};
};
Creating your own stores
If you want to add additional stores, you should do the following:
- Create a new directory in
/client/store
and name it appropriately, e.g.posts
- In that folder create a file named
postsActions.tsx
andpostsReducer.tsx
. - In the actions file, declare all your dispatch functions
- Export new constants for all you actions in
/client/store/actionTypes.tsx
- Declare the store setup in the reducer file
- Import the store in
/client/store/store.tsx
and add it to thecombineReducers
function. - DONE!