Example 1: redux action
import { createActions, handleActions, combineActions } from 'redux-actions';
const defaultState = { counter: 10 };
const { increment, decrement } = createActions({
INCREMENT: (amount = 1) => ({ amount }),
DECREMENT: (amount = 1) => ({ amount: -amount })
});
const reducer = handleActions({
[combineActions(increment, decrement)]: (state, action) => {
return { ...state, counter: state.counter + action.payload.amount };
}
},
defaultState
);
export default reducer;
Example 2: redux dispatch input onchange
const SearchBar = ({ searchQuery }) =>
<Card>
<div className={styles.searchFieldContainer}>
<div className={styles.field}>
<input type="text" onChange={(event)=> searchQuery(event.target.value)} placeholder="Search for items or sellers" />
</div>
<Button className={styles.searchButton}>
Search
</Button>
</div>
</Card>
const mapStateToProps = () => {
return {
}
}
const mapDispatchToProps = (dispatch) => {
return {
searchQuery: (val) => dispatch(searchQuery(val))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
Example 3: react return action in a function
import React, {useState} from 'react';
function newCallback(callback) {
callback('This can be any value you want to return')
}
const Callback = () => {
const [callbackData, setCallbackData] = useState('')
function actionAferCallback (callback) {
setCallbackData(callback)
}
function requestCallback() {
newCallback(actionAferCallback)
}
return(
<div>
{}
<button onClick={() => {requestCallback()}}>Request Callback</button>
{callbackData}
</div>
)
}
export default Callback;
Example 4: redux acions
export const incAsyncCreator = createAction("INC");
export const decAsyncCreator = createAction("DEC");
export const incReducer = handleAction(
incAsyncCreator,
(state, action) => ({
...state,
counter: state.counter + 1,
success: action.payload.success
}),
counterState
);
export const decReducer = handleAction(
incAsyncCreator,
(state, action) => ({
...state,
counter: state.counter + 1,
success: action.payload.success
}),
counterState
);
export const { increment, decrement } = createActions({
increment: (payload) => ({ ...payload }),
decrement: (payload) => ({ ...payload })
});
export const counterReducer = handleActions(
{
[increment]: (state, action) => ({
...state,
counter: state.counter + 1,
success: action.payload.success
}),
[decrement]: (state, action) => ({
...state,
counter: state.counter - 1,
success: action.payload.success
})
},
counterState
);
Example 5: what is dispatch in redux
function dispatch(action) {
if (typeof action !== 'object' || obj === null) {
throw new Error('actions must be plain object.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property.');
}
reducer(currentState, action);
}