Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
setState is One Step Behind onChange
To make sure that we set our state sequentially within a React component, we can pass in a callback as a 2nd argument of setState
.
The callback is run when the value in the first argument is set as the new state value.
For instance, we can write:
handleChange(e) {
this.setState({ name: e.target.value }, this.handleSubmit);
}
We update the name
state with our inputted value.
And then we call the handleSubmit
method, which is a method that’s called after the name
state is set.
In function components, we can write:
useEffect(() => {
//...
}, [name]);
to run the callback when the name
state changes.
How to Sync Props to State using React Hooks
To sync prop values to state in a function component, we can use the useEffect
hook to watch for prop value changes.
Then the callback we pass into the hook is run and when the prop value changes.
For instance, we can write:
import React,{useState , useEffect} from 'react';
const Persons = ({ name }) => {
const [nameState , setNameState] = useState(name);
useEffect(() => {
setNameState(name);
}, [name])
return (
<div>
<p>My name is {props.name}</p>
<p>My name is {nameState}</p>
</div>
)
}
We have the Persons
component that takes a name
prop.
We set the initial state with the useState
hook by passing in our prop value to it.
Then we added a useEffect
hook to listen to the name
value for changes.
If it changes, the callback is run.
We call setNameState
to update the nameState
with the latest name
value.
Then we display both the prop and the state value.
Use Redux to Refresh a JSON Web Token
To use redux to refresh a JSON web token, we’ve to create a thunk and use the Redux thunk middleware.
To do that, we can write:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { reducer } from './reducer';
const rootReducer = combineReducers({
reducer
//...
})
const store = createStore(rootReducer, applyMiddleware(thunk));
to apply the thunk middleware in our store.
Then we can create our reducer by witing:
reducer.js
const initialState = {
fetching: false,
};
export function reducer(state = initialState, action) {
switch(action.type) {
case 'LOAD_FETCHING':
return {
...state,
fetching: action.fetching,
}
}
}
We have a reducer that stores the fetching
state.
Then we can create our think by writing:
export function loadData() {
return (dispatch, getState) => {
const { auth, isLoading } = getState();
if (!isExpired(auth.token)) {
dispatch({ type: 'LOAD_FETCHING', fetching: false })
dispatch(loadProfile());
} else {
dispatch({ type: 'LOAD_FETCHING', fetching: true })
dispatch(refreshToken());
}
};
}
We created a thunk that calls dispatch
and also gets the state to check if we need to get the token with the refresh token.
A thunk returns a function with the dispatch
function to dispatch actions and getState
to get the state.
And then we can dispatch the thunk by writing:
componentDidMount() {
dispath(loadData());
}
in our component.
There’s also the redux-api-middleware package that we can add as a middleware to our React app.
We can install it by running:
npm i redux-api-middleware
Then we can create an action with it by writing:
import { createAction } from `redux-api-middleware`;
const getToken = () => createAction({
endpoint: 'http://www.example.com/api/token',
method: 'GET',
types: ['REQUEST', 'SUCCESS', 'FAILURE']
})
export { getToken };
type
is a string that tells what action has occurred.
We also pass in the endpoint
with the URL, and method
with the request method.
We can add the middleware by writing:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { apiMiddleware } from 'redux-api-middleware';
import reducers from './reducers';
const reducer = combineReducers(reducers);
const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);
export default function configureStore(initialState) {
return createStoreWithMiddleware(reducer, initialState);
}
We import the reducers
and the middleware and incorporate them into our store.
Then we can use the action that we created with createAction
.
Conclusion
There are several ways to get a token with Redux.
Also, we can run code after setState
is done.
And we can watch for prop value changes and update the state accordingly.