React redux dispatch action to connect to mqtt - reactjs

I am building an react application to connect to and display data from a MQTT server.
I have implemented the basic connection code in mqtt/actions.js See below:
const client = mqtt.connect(options);
client.on('connect', function () {
mqttConnectionState('MQTT_CONNECTED')
client.subscribe(['btemp', 'otemp'], (err, granted) => {
if (err) alert(err)
console.log(`Subscribed to: otemp & btemp topics`)
})
})
client.on('message', function (topic, message) {
updateTemp({topic: topic, value: message.toString()})
});
const mqttConnectionState = (action, err = null) => {
return {
type: action,
payload: err
}
}
I am looking to on button press initiate the mqtt connection and then dispatch a connection success event.
However with the above code I am unsure exactly how this would work.
I could move the connect line const client = mqtt.connect(options); to a function and run that function on button click but then then the client.on functions will not be able to see the client const.
How is best to approach this?
I am using React.JS, Redux and the MQTT.JS libraries.
Update: Trying to dispatch and action when a message is received
Reducer:
const createClient = () => {
const client = mqtt.connect(options);
client.on('connect', function () {
mqttConnectionState('MQTT_CONNECTED')
client.subscribe(['btemp', 'otemp'], (err, granted) => {
if (err) alert(err)
console.log(`Subscribed to: otemp & btemp topics`)
});
});
client.on('message', (topic, message) => {
console.log('message received from mqtt')
processMessage({topic, message})
})
return client;
}
case MESSAGE_RECEIVED:
console.log('message received')
messageReceived(payload)
return state;
Actions:
export const processMessage = (data) => dispatch => {
console.log('Processing Message')
return {
type: 'MESSAGE_RECEIVED',
payload: data
}
}
message received from mqtt log each time a message arrives, however processMessage({topic, message}) never executes as Processing Message never logs to the console

"Actions are payloads of information that send data from your application to your store" (docs)
So you have to create the client in the Reducer (his function). Put it on the Redux state like this:
initialState = {
client: null
}
and you reducer.js file should look like this:
import {
mqttConnectionState
} from './actions'
 
 
let initialState = {
client: null ,
err: null
}
const createClient = () => {
const client = mqtt.connect(options);
client.on('connect', function () {
mqttConnectionState('MQTT_CONNECTED')
client.subscribe(['btemp', 'otemp'], (err, granted) => {
if (err) alert(err)
console.log(`Subscribed to: otemp & btemp topics`)
});
});
return client;
}
function app(state = initialState, action) {
switch (action.type) {
case 'INIT_CONNECTION':
return {
...state,
client: createClient()
})
case 'MQTT_CONNECTED':
return {
...state,
err: action.payload
})
default:
return state
}
}
and you actions.js:
...
const mqttConnectionInit = () => {
return {
type: 'INIT_CONNECTION'
}
}
const mqttConnectionState = (err = null) => {
return {
type: 'MQTT_CONNECTED',
payload: err
}
}
...
this way you can dispatch the action mqttConnectionInit in the onclick button event.

Dispatching Redux actions inside a reducer may clear your store. I mean, setting it's state to what you have under initialState. And require cycles are no-op.
Yesterday I did some changes in my code, because I've tried solution above and ended up with a warning "require cycles are allowed but can result in uninitialized values". I moved mqtt connection related code into the middleware.
import { DEVICE_TYPE, HOST, PASSWORD, PORT, USER_NAME } from '../utils/variables';
import { mqttConnectionInit, mqttConnectionState } from '../actions/devices';
import mqtt from 'mqtt/dist/mqtt';
import { SIGNED_IN } from '../constants/types';
const MqttMiddleware = store => next => action => {
if (action.type == SIGNED_IN) {
store.dispatch(mqttConnectionInit());
const client = mqtt.connect(`ws://${HOST}:${PORT}`, { username: USER_NAME, password: PASSWORD });
client.on('connect', function () {
let license = store.getState().auth.license;
store.dispatch(mqttConnectionState(client));
client.subscribe(`/${USER_NAME}/${license}/+/${DEVICE_TYPE}/#`);
});
client.on('message', ((topic, payload) => {
const device = JSON.parse(message(topic, payload.toString()));
console.log(device);
}));
}
next(action);
};
export function message(message, value) {
const msg = message.split('/');
return JSON.stringify({
"id": msg[3],
"user": msg[1],
"license": msg[2],
"type": msg[4],
"name": msg[5],
"value": value == "0" ? 0 : (value.match(/[A-Za-z]/) ? value : Number(value))
});
}
export default MqttMiddleware;
You can do pretty much all you want with the store.
actions.js
import { INIT_CONNECTION, MQTT_CONNECTED } from '../constants/types'
export const mqttConnectionInit = () => {
return {
type: INIT_CONNECTION
}
}
export const mqttConnectionState = (client, err = null) => {
return {
type: MQTT_CONNECTED,
error: err,
client: client,
}
}
reducers.js
import { INIT_CONNECTION, MQTT_CONNECTED } from '../constants/types';
const mqttReducer = (state = initialState, action) => {
switch (action.type) {
case INIT_CONNECTION:
return {
...state,
client: null,
};
case MQTT_CONNECTED:
return {
...state,
err: action.error,
client: action.client,
};
default:
return state;
}
}
const initialState = {
client: null,
err: null,
}
export default mqttReducer;

Related

does anyone know how to integrate mqtt integration in react using react redux to dispatch the actions and store client payload as a mqttClient object?

Basically i wanted to integrate the mqtt in my react app. I want to connect to the mqtt when user login and disconnect when user logs out.
Firstly i created actions,reducers to dispatch the connection state and get client payload. It's connecting but the mqtt servers seems to be reconnecting in a loop with few secs. I want it to connect once and disconnect user logs out automatically. I globally initiated the mqtt client in the mqqtActions.js.
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
import mqtt from 'mqtt'
const mqttHost = "host ip address here";
const mqttPort = 8083;
const mqttUrl = `ws://${mqttHost}:${mqttPort}/mqtt`
const mqttOptions = {
keepalive: 30,
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clientId: "bharath",
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
},
rejectUnauthorized: false
};
const mqttClient = mqtt.connect(mqttUrl, mqttOptions)
export const mqttConnect = () => async (dispatch) => {
try {
dispatch({
type: CONNECT_MQTT_REQUEST
})
dispatch({
type: CONNECT_MQTT_SUCCESS,
payload: mqttClient
})
//mqttClient.connect()
localStorage.setItem('mqttClient', JSON.stringify(mqttClient))
} catch (error) {
dispatch({
type: CONNECT_MQTT_FAILURE,
payload: error.response && error.response.data.message ? error.response.data.message : error.message
})
}
}
export const mqttDisconnect = () => (dispatch) => {
try {
dispatch({ type: DISCONNECT_MQTT_REQUEST })
mqttClient.end()
localStorage.removeItem('mqttClient')
dispatch({
type: DISCONNECT_MQTT_SUCCESS,
})
} catch (error) {
dispatch({
type: DISCONNECT_MQTT_FAILURE,
payload: error.response && error.response.data.message ? error.response.data.message : error.message
})
}
}
I set up my reducer file like this:
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
export const connectMqttReducer = (state = {}, action) => {
switch (action.type) {
case CONNECT_MQTT_REQUEST:
return { status: 'connecting' }
case CONNECT_MQTT_SUCCESS:
return { status: 'connected', client: action.payload }
case CONNECT_MQTT_FAILURE:
return { status: 'connect', error: action.payload }
default:
return state
}
}
export const disconnectMqttReducer = (state = {}, action) => {
switch (action.type) {
case DISCONNECT_MQTT_REQUEST:
return { status: 'connected' }
case DISCONNECT_MQTT_SUCCESS:
return { status: 'connect' }
case DISCONNECT_MQTT_FAILURE:
return { status: 'connected', error: action.payload }
default:
return state
}
}
Doing this i'm able to connect but its timestamp when connectedAt is changing continously.And also mqtt.connect() is not function error is also showing. I commented it out. I want to connect it once and disconnect when user login and logout actions are triggered.
Please try the following:
1- Add the following to your environment file:
MQTT_HOST="host ip address here"
MQTT_PORT=8083
2- Add the following in your Constants.js file:
export const mqttUrl = `ws://${process.env.MQTT_HOST}:${process.env.MQTT_PORT}/mqtt`;
export const mqttOptions = {
keepalive: 30,
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
clientId: 'bharath',
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false,
},
rejectUnauthorized: false,
};
export const localStorageKeys = {
mqttClient: 'mqttClient',
};
3- Create a new file which will hold all mqtt functionality /src/clients/MqttClient.js:
import mqtt from 'mqtt';
import { localStorageKeys, mqttOptions, mqttUrl } from '#/js/constants/Helpers';
let instance = null;
class MqttClient {
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
myMqtt;
connect() {
this.myMqtt = mqtt.connect(mqttUrl, mqttOptions);
return new Promise((resolve, reject) => {
this.myMqtt.on('connect', () => {
//add instance to local storage if it's not present (if you need it)
const localStorageMqtt = localStorage.getItem(localStorageKeys.mqttClient);
if (localStorageMqtt === null) {
localStorage.setItem(localStorageKeys.mqttClient, JSON.stringify(this.myMqtt));
}
resolve();
});
this.myMqtt.on('error', (error) => reject(error));
});
}
disconnect() {
return new Promise((resolve) => {
this.myMqtt.end(false, {}, () => {
this.myMqtt = null;
//if you added it to the localstorage (on connect)
localStorage.removeItem(localStorageKeys.mqttClient);
resolve();
});
});
}
subscribe(event) {
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
return this.myMqtt.subscribe(event, (err) => {
// Optional callback that you can use to detect if there's an error
if (err) {
console.error(err);
return reject(err);
}
return resolve();
});
});
}
publish(event, data) {
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
return this.myMqtt.publish(event, data, {}, (err) => {
// Optional callback that you can use to detect if there's an error
if (err) {
console.error(err);
return reject(err);
}
return resolve();
});
});
}
on(event, fun) {
// No promise is needed here, but we're expecting one in the middleware.
return new Promise((resolve, reject) => {
if (!this.myMqtt) return reject('No mqtt connection.');
this.myMqtt.on(event, fun);
resolve();
});
}
}
export default MqttClient;
4- Create a new mqtt middleware in your store directory /src/store/middleWares/MqttMiddleWare.js:
export const mqttMiddleWare =
(mqtt) =>
({ dispatch, getState }) =>
(next) =>
(action) => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
/*
* Mqtt middleware usage.
* promise: (mqtt) => mqtt.connect()
* type: 'mqtt' //always (mqtt)
* types: [REQUEST, SUCCESS, FAILURE]
*/
const { promise, type, types, ...rest } = action;
if (type !== 'mqtt' || !promise) {
// Move on! Not a mqtt request or a badly formed one.
return next(action);
}
const [REQUEST, SUCCESS, FAILURE] = types;
next({ ...rest, type: REQUEST });
return promise({ mqtt, dispatch, getState })
.then((result) => {
return next({ ...rest, result, type: SUCCESS });
})
.catch((error) => {
console.log(error);
return next({ ...rest, error, type: FAILURE });
});
};
5- Update your store config to accept mqtt client as an argument then pass it to the mqtt middleware as follows /src/store/configureStore.js:
const middlewares = [];
// log redux data in development mode only
if (process.env.NODE_ENV !== 'production') {
const { logger } = require('redux-logger');
middlewares.push(logger);
}
const configureStore = (mqttClient) => {
const store = createStore(
rootReducer,
/* preloadedState, */
composeWithDevTools(
applyMiddleware(thunkMiddleware, mqttMiddleWare(mqttClient), ...middlewares)
)
);
return store;
};
export default configureStore;
6- Instantiate your mqtt client in /src/index.jsx and pass it to your store:
const mqttClient = new MqttClient();
const store = configureStore(mqttClient);
7- Update your reducer as follows:
import { CONNECT_MQTT_FAILURE, CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE, DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS } from "../constants/mqttConstants"
export const connectMqttReducer = (state = {}, action) => {
switch (action.type) {
case CONNECT_MQTT_REQUEST:
return { connectionStatus: 'connecting' }
case CONNECT_MQTT_SUCCESS:
return { connectionStatus: 'connected' }
case CONNECT_MQTT_FAILURE:
return { connectionStatus: 'connect failed', error: action.error }
default:
return state
}
}
export const disconnectMqttReducer = (state = {}, action) => {
switch (action.type) {
case DISCONNECT_MQTT_REQUEST:
return { disconnectionStatus: 'disconnecting' }
case DISCONNECT_MQTT_SUCCESS:
return { disconnectionStatus: 'disconnected' }
case DISCONNECT_MQTT_FAILURE:
return { disconnectionStatus: 'connect failed', error: action.error }
default:
return state
}
}
8- Update your actions as follows:
Connect action:
export const startMqttConnection = () => ({
type: 'mqtt',
types: [CONNECT_MQTT_REQUEST, CONNECT_MQTT_SUCCESS, CONNECT_MQTT_FAILURE],
promise: ({ mqtt }) => mqtt.connect(),
});
Disconnect action:
export const stopMqttConnection = () => ({
type: 'mqtt',
types: [DISCONNECT_MQTT_REQUEST, DISCONNECT_MQTT_SUCCESS, DISCONNECT_MQTT_FAILURE],
promise: ({ mqtt }) => mqtt.disconnect(),
});
9- dispatch the required action as follows:
useEffect(() => {
dispatch(startMqttConnection());
return () => {
if (connectionStatus === 'connected') {
dispatch(stopMqttConnection());
}
};
//eslint-disable-next-line
}, [dispatch]);

useEffect not firing on chained dispatch (chained yield put from redux-saga)

Libraries used: redux and redux-saga.
On one of my components I have the useEffect hook that has the dependency set to the status of an API request. That useEffect is then triggering a toast notification based on whether the API request is successful or failed.
But, this useEffect is not firing on each yield put called by the redux-saga defined below.
My intention is the following:
Fire the useEffect in the component after the yield put requestSuccessful(...) or yield put requestFailed(...)
After that, fire the useEffect once again after the yield put initResponseFlags(...)
What's happening currently is that my useEffect is not called at all. I'm assuming it's probably because the yield(s) inside the saga change the redux state so fast (from false to true and then false again) that useEffect is not being able to catch the change.
Places.js (component)
const { places, message, waiting, success, error } = useSelector(state => ({
places: state.Places.data.places,
message: state.Places.requestStatus.message,
waiting: state.Places.requestStatus.waiting,
success: state.Places.requestStatus.success,
error: state.Places.requestStatus.error,
}));
...
useEffect(() => {
console.log("useEffect called");
if (success || error) {
// ... toast message ...
console.log("Firing");
}
}, [dispatch, success, error, message, waiting]);
My project uses the redux-saga library and it contains a generic saga for each API request being made in the app.
saga.js
function* requestStart(args, params) {
if (!params || !params.payload || !params.payload.action)
throw Object.assign(
new Error(`Get action params and payload have not been defined!`),
{ code: 400 }
);
let action = params.payload.action;
let actionPayload = params.payload.actionPayload;
let actions = params.payload.actions;
try {
if (process.env.REACT_APP_API_URL) {
if (actions?.beforeStart) {
yield put(putAction(actions?.beforeStart));
}
const { response, error } = yield call(action, actionPayload);
if (response !== undefined) {
yield put(requestSuccessful(args.namespace, response));
if (actions?.onSuccess) {
yield put(putAction(actions?.onSuccess, response));
}
} else {
yield put(requestFailed(args.namespace, error));
if (actions?.onFailure) {
yield put(putAction(actions?.onFailure, error));
}
}
}
} catch (error) {
yield put(requestFailed(args.namespace, error));
if (args.actions?.onFailure) {
yield put(putAction(params.actions?.onFailure, error));
}
} finally {
yield put(initResponseFlags(args.namespace));
}
}
actions.js
export const initResponseFlags = (namespace) => {
return {
type: `${namespace}/${INIT_RESPONSE_FLAGS}`,
};
};
export const requestStart = (namespace, payload) => {
return {
type: `${namespace}/${REQUEST_START}`,
payload: payload,
};
};
export const requestSuccessful = (namespace, payload) => {
return {
type: `${namespace}/${REQUEST_SUCCESSFUL}`,
payload: payload
};
};
export const requestFailed = (namespace, error) => {
return {
type: `${namespace}/${REQUEST_FAILED}`,
payload: error
};
};
reducer.js
import {
INIT_RESPONSE_FLAGS,
REQUEST_START,
REQUEST_SUCCESSFUL,
REQUEST_FAILED,
} from "./actionTypes";
const initialState = {
message: null,
waiting: false,
success: false,
error: false,
};
const RequestStatus = (namespace) => (state = initialState, action) => {
switch (action.type) {
case `${namespace}/${INIT_RESPONSE_FLAGS}`:
state = {
...state,
message: null,
waiting: false,
success: false,
error: false,
};
break;
case `${namespace}/${REQUEST_START}`:
state = {
...state,
waiting: true,
};
break;
case `${namespace}/${REQUEST_SUCCESSFUL}`:
state = {
...state,
waiting: false,
success: true,
error: false,
};
break;
case `${namespace}/${REQUEST_FAILED}`:
state = {
...state,
waiting: false,
message: action.payload,
success: false,
error: true
};
break;
default: break;
}
return state;
};
export default RequestStatus;
EDIT (12.10.2022. 11:08)
I've just inserted a yield delay(1); of 1ms before my yield put(initResponseFlags(...)); and it works now.
Alas, if there's some other solution (cause this seems like it's botched) - any help would be appreciated!
saga.js
function* requestStart(args, params) {
if (!params || !params.payload || !params.payload.action)
throw Object.assign(
new Error(`Get action params and payload have not been defined!`),
{ code: 400 }
);
let action = params.payload.action;
let actionPayload = params.payload.actionPayload;
let actions = params.payload.actions;
try {
if (process.env.REACT_APP_API_URL) {
if (actions?.beforeStart) {
yield put(putAction(actions?.beforeStart));
}
const { response, error } = yield call(action, actionPayload);
if (response !== undefined) {
console.log('kitica');
yield put(requestSuccessful(args.namespace, response));
if (actions?.onSuccess) {
yield put(putAction(actions?.onSuccess, response));
}
} else {
yield put(requestFailed(args.namespace, error));
if (actions?.onFailure) {
yield put(putAction(actions?.onFailure, error));
}
}
}
} catch (error) {
yield put(requestFailed(args.namespace, error));
if (args.actions?.onFailure) {
yield put(putAction(params.actions?.onFailure, error));
}
} finally {
yield delay(1);
yield put(initResponseFlags(args.namespace));
}
}

How to use an action within reducer?

So I am making a connection to a MQTT broker via Redux. I have three actions, one making the connection, another one checking for error and one receiving the message.
Only the first one gets triggered and the other 2 do not trigger. The connection is successful.
Here is my code:
Actions
export const mqttConnectionInit = (topic) => {
return {
type: 'INIT_CONNECTION',
topic:topic
}
}
export const mqttConnectionState = (err = null) => {
return {
type: 'MQTT_CONNECTED',
payload: err
}
}
export const processMessage = (data) => dispatch => {
console.log('Receiving Message')
return {
type: 'MESSAGE_RECEIVED',
payload: data
}
}
Reducer
import { mqttConnectionState} from './mqttActions'
import { processMessage} from './mqttActions'
const initState = {
client: null,
err: null,
message : 'message'
}
const createClient = (topic) => {
const mqtt = require('mqtt')
const client = mqtt.connect('ws://localhost:9001');
client.on('connect', function () {
mqttConnectionState('MQTT_CONNECTED')
client.subscribe(topic, (err, granted) => {
if (err) alert(err)
console.log(`Subscribed to: ` + topic)
console.log(granted)
});
});
//messages recevied during subscribe mode will be output here
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
processMessage({topic, message})
// client.end() will stop the constant flow of values
})
return client;
}
const mqttReducer = (state = initState, action) =>{
switch (action.type) {
case 'INIT_CONNECTION':
return {
...state,
client: createClient(action.topic)
}
case 'MQTT_CONNECTED':
return {
...state,
err: action.payload
}
case 'MESSAGE_RECEIVED':
return {
...state,
message: action.payload //payload:data
}
default:
return state
}
}
export default mqttReducer
Why mqttConnectionState and processMessage do not get triggered?
You can never call async logic from within a reducer! Your createClient method is entirely async logic, and so it cannot go in a reducer.
In addition, you should not put non-serializable values into the Redux store.
Instead, we recommend that persistent connections like sockets should go into middleware.

how to async/await redux-thunk actions?

action.js
export function getLoginStatus() {
return async(dispatch) => {
let token = await getOAuthToken();
let success = await verifyToken(token);
if (success == true) {
dispatch(loginStatus(success));
} else {
console.log("Success: False");
console.log("Token mismatch");
}
return success;
}
}
component.js
componentDidMount() {
this.props.dispatch(splashAction.getLoginStatus())
.then((success) => {
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
});
}
However, when I write component.js code with async/await like below I get this error:
Possible Unhandled Promise Rejection (id: 0): undefined is not a function (evaluating 'this.props.dispatch(splashAction.getLoginStatus())')
component.js
async componentDidMount() {
let success = await this.props.dispatch(splashAction.getLoginStatus());
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
}
How do I await a getLoginStatus() and then execute the rest of the statements?
Everything works quite well when using .then(). I doubt something is missing in my async/await implementation. trying to figure that out.
The Promise approach
export default function createUser(params) {
const request = axios.post('http://www...', params);
return (dispatch) => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
request.then(success => onSuccess, error => onError);
};
}
The async/await approach
export default function createUser(params) {
return async dispatch => {
function onSuccess(success) {
dispatch({ type: CREATE_USER, payload: success });
return success;
}
function onError(error) {
dispatch({ type: ERROR_GENERATED, error });
return error;
}
try {
const success = await axios.post('http://www...', params);
return onSuccess(success);
} catch (error) {
return onError(error);
}
}
}
Referenced from the Medium post explaining Redux with async/await: https://medium.com/#kkomaz/react-to-async-await-553c43f243e2
Remixing Aspen's answer.
import axios from 'axios'
import * as types from './types'
export function fetchUsers () {
return async dispatch => {
try {
const users = await axios
.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.data)
dispatch({
type: types.FETCH_USERS,
payload: users,
})
} catch (err) {
dispatch({
type: types.UPDATE_ERRORS,
payload: [
{
code: 735,
message: err.message,
},
],
})
}
}
}
import * as types from '../actions/types'
const initialErrorsState = []
export default (state = initialErrorsState, { type, payload }) => {
switch (type) {
case types.UPDATE_ERRORS:
return payload.map(error => {
return {
code: error.code,
message: error.message,
}
})
default:
return state
}
}
This will allow you to specify an array of errors unique to an action.
Another remix for async await redux/thunk. I just find this a bit more maintainable and readable when coding a Thunk (a function that wraps an expression to delay its evaluation ~ redux-thunk )
actions.js
import axios from 'axios'
export const FETCHING_DATA = 'FETCHING_DATA'
export const SET_SOME_DATA = 'SET_SOME_DATA'
export const myAction = url => {
return dispatch => {
dispatch({
type: FETCHING_DATA,
fetching: true
})
getSomeAsyncData(dispatch, url)
}
}
async function getSomeAsyncData(dispatch, url) {
try {
const data = await axios.get(url).then(res => res.data)
dispatch({
type: SET_SOME_DATA,
data: data
})
} catch (err) {
dispatch({
type: SET_SOME_DATA,
data: null
})
}
dispatch({
type: FETCHING_DATA,
fetching: false
})
}
reducers.js
import { FETCHING_DATA, SET_SOME_DATA } from './actions'
export const fetching = (state = null, action) => {
switch (action.type) {
case FETCHING_DATA:
return action.fetching
default:
return state
}
}
export const data = (state = null, action) => {
switch (action.type) {
case SET_SOME_DATA:
return action.data
default:
return state
}
}
Possible Unhandled Promise Rejection
Seems like you're missing the .catch(error => {}); on your promise. Try this:
componentDidMount() {
this.props.dispatch(splashAction.getLoginStatus())
.then((success) => {
if (success == true) {
Actions.counter()
} else {
console.log("Login not successfull");
}
})
.catch(err => {
console.error(err.getMessage());
}) ;
}
use dispatch(this.props.splashAction.getLoginStatus()) instead this.props.dispatch(splashAction.getLoginStatus())

How to store client in redux?

I'm setting up a redux application that needs to create a client. After initialization, the client has listeners and and APIs that will need to be called based on certain actions.
Because of that I need to keep an instance of the client around. Right now, I'm saving that in the state. Is that right?
So I have the following redux action creators, but then when I want to send a message I need to call the client.say(...) API.
But where should I get the client object from? Should I retrieve the client object from the state? My understanding is that that's a redux anti-pattern. What's the proper way to do this with redux?
Even stranger – should the message send be considered an action creator when it doesn't actually mutate the state?
The actions:
// actions.js
import irc from 'irc';
export const CLIENT_INITIALIZE = 'CLIENT_INITIALIZE';
export const CLIENT_MESSAGE_RECEIVED = 'CLIENT_MESSAGE_RECEIVED';
export const CLIENT_MESSAGE_SEND = 'CLIENT_MESSAGE_SEND';
export function messageReceived(from, to, body) {
return {
type: CLIENT_MESSAGE_RECEIVED,
from: from,
to: to,
body: body,
};
};
export function clientSendMessage(to, body) {
client.say(...); // <--- where to get client from?
return {
type: CLIENT_MESSAGE_SEND,
to: to,
body: body,
};
};
export function clientInitialize() {
return (dispatch) => {
const client = new irc.Client('chat.freenode.net', 'react');
dispatch({
type: CLIENT_INITIALIZE,
client: client,
});
client.addListener('message', (from, to, body) => {
console.log(body);
dispatch(messageReceived(from, to, body));
});
};
};
And here is the reducer:
// reducer.js
import { CLIENT_MESSAGE_RECEIVED, CLIENT_INITIALIZE } from '../actions/client';
import irc from 'irc';
export default function client(state: Object = { client: null, channels: {} }, action: Object) {
switch (action.type) {
case CLIENT_MESSAGE_RECEIVED:
return {
...state,
channels: {
...state.channels,
[action.to]: [
// an array of messages
...state.channels[action.to],
// append new message
{
to: action.to,
from: action.from,
body: action.body,
}
]
}
};
case CLIENT_JOIN_CHANNEL:
return {
...state,
channels: {
...state.channels,
[action.channel]: [],
}
};
case CLIENT_INITIALIZE:
return {
...state,
client: action.client,
};
default:
return state;
}
}
Use middleware to inject the client object into action creators! :)
export default function clientMiddleware(client) {
return ({ dispatch, getState }) => {
return next => (action) => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
const { promise, ...rest } = action;
if (!promise) {
return next(action);
}
next({ ...rest });
const actionPromise = promise(client);
actionPromise.then(
result => next({ ...rest, result }),
error => next({ ...rest, error }),
).catch((error) => {
console.error('MIDDLEWARE ERROR:', error);
next({ ...rest, error });
});
return actionPromise;
};
};
}
Then apply it:
const client = new MyClient();
const store = createStore(
combineReducers({
...
}),
applyMiddleware(clientMiddleware(client))
);
Then you can use it in action creators:
export function actionCreator() {
return {
promise: client => {
return client.doSomethingPromisey();
}
};
}
This is mostly adapted from the react-redux-universal-hot-example boilerplate project. I removed the abstraction that lets you define start, success and fail actions, which is used to create this abstraction in action creators.
If your client is not asynchronous, you can adapt this code to simply pass in the client, similar to how redux-thunk passes in dispatch.

Resources