Redux-saga firebase onAuthStateChanged eventChannel - firebase

How to handle firebase auth state observer in redux saga?
firebase.auth().onAuthStateChanged((user) => {
});
I want to run APP_START saga when my app starts which will run firebase.auth().onAuthStateChanged observer and will run other sagas depending on the callback.
As I understand eventChannel is right way to do it. But I don't understand how to make it work with firebase.auth().onAuthStateChanged.
Can someone show how to put firebase.auth().onAuthStateChanged in to eventChannel?

You can use eventChannel. Here is an example code:
function getAuthChannel() {
if (!this.authChannel) {
this.authChannel = eventChannel(emit => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => emit({ user }));
return unsubscribe;
});
}
return this.authChannel;
}
function* watchForFirebaseAuth() {
...
// This is where you wait for a callback from firebase
const channel = yield call(getAuthChannel);
const result = yield take(channel);
// result is what you pass to the emit function. In this case, it's an object like { user: { name: 'xyz' } }
...
}
When you are done, you can close the channel using this.authChannel.close().

Create your own function onAuthStateChanged() that will return a Promise
function onAuthStateChanged() {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
resolve(user);
} else {
reject(new Error('Ops!'));
}
});
});
}
Then use call method to get the user synchronously
const user = yield call(onAuthStateChanged);

This could be handled in the Saga such as the following for Redux Saga Firebase:
// Redux Saga: Firebase Auth Channel
export function* firebaseAuthChannelSaga() {
try {
// Auth Channel (Events Emit On Login And Logout)
const authChannel = yield call(reduxSagaFirebase.auth.channel);
while (true) {
const { user } = yield take(authChannel);
// Check If User Exists
if (user) {
// Redux: Login Success
yield put(loginSuccess(user));
}
else {
// Redux: Logout Success
yield put(logoutSuccess());
}
}
}
catch (error) {
console.log(error);
}
};

here is how you would run the onAuthStateChanged observable using redux-saga features (mainly eventChannel)
import { eventChannel } from "redux-saga";
import { take, call } from "redux-saga/effects";
const authStateChannel = function () {
return eventChannel((emit) => {
const unsubscribe = firebase.auth().onAuthStateChanged(
(doc) => emit({ doc }),
(error) => emit({ error })
);
return unsubscribe;
});
};
export const onAuthStateChanged = function* () {
const channel = yield call(authStateChannel);
while (true) {
const { doc, error } = yield take(channel);
if (error) {
// handle error
} else {
if (doc) {
// user has signed in, use `doc.toJSON()` to check
} else {
// user has signed out
}
}
}
};
please note that other solutions that don't utilize channel sagas are not optimal for redux-saga, because turning an observable into a promise is not a valid solution in this case since you would need to call the promise each time you anticipate a change in authentication state (like for example: taking every USER_SIGNED_IN action and calling the "promisified" observable), which will negate the whole purpose of an observable

Related

How to get stripe customers in next js

I am using Stripe in my NextJs project and have tried to get customers list in my app but have not succeeded. If anyone knows how to get it, please instruct me on how to do that.
This is my code:
import { loadStripe } from "#stripe/stripe-js";
async function getStripeCustomers(){
const stripe = await loadStripe(
process.env.key
);
if (stripe) {
// there was a toturail for node.js like this.
console.log(stripe.customers.list())
}
}
useEffect(() => {
getStripeCustomers()
}, []);
I think you should do this logic in backend so create a route in api folder then try this code.
// api/payment/get-all-customers.js
import Stripe from "stripe";
export default async function handler(req, res) {
if (req.method === "POST") {
const { token } = JSON.parse(req.body);
if (!token) {
return res.status(403).json({ msg: "Forbidden" });
}
const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET, {
apiVersion: "2020-08-27",
});
try {
const customers = await stripe.customers.list(); // returns all customers sorted by createdDate
res.status(200).json(customers);
} catch (err) {
console.log(err);
res.status(500).json({ error: true });
}
}
}
Now from frontend send a POST request to newly created route.

Handling errors with redux-toolkit

The information about the error in my case sits deeply in the response, and I'm trying to move my project to redux-toolkit. This is how it used to be:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}
The problem is that redux-toolkit doesn't put that data in the rejected action creator and I have no access to the error message, it puts his message instead of the initial one:
While the original response looks like this:
So how can I retrieve that data?
Per the docs, RTK's createAsyncThunk has default handling for errors - it dispatches a serialized version of the Error instance as action.error.
If you need to customize what goes into the rejected action, it's up to you to catch the initial error yourself, and use rejectWithValue() to decide what goes into the action:
const updateUser = createAsyncThunk(
'users/update',
async (userData, { rejectWithValue }) => {
const { id, ...fields } = userData
try {
const response = await userAPI.updateById(id, fields)
return response.data.user
} catch (err) {
if (!err.response) {
throw err
}
return rejectWithValue(err.response.data)
}
}
)
We use thunkAPI, the second argument in the payloadCreator; containing all of the parameters that are normally passed to a Redux thunk function, as well as additional options: For our example async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) is our payloadCreator with the required arguments;
This is an example using fetch api
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
export const getExampleThunk = createAsyncThunk(
'auth/getExampleThunk',
async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) => {
try{
const response = await fetch('https://reqrefs.in/api/users/yu');
if (!response.ok) {
return rejectWithValue(response.status)
}
const data = await response.json();
return fulfillWithValue(data)
}catch(error){
throw rejectWithValue(error.message)
}
}
)
Simple example in slice:
const exampleSlice = createSlice({
name: 'example',
initialState: {
httpErr: false,
},
reducers: {
//set your reducers
},
extraReducers: {
[getExampleThunk.pending]: (state, action) => {
//some action here
},
[getExampleThunk.fulfilled]: (state, action) => {
state.httpErr = action.payload;
},
[getExampleThunk.rejected]: (state, action) => {
state.httpErr = action.payload;
}
}
})
Handling Error
Take note:
rejectWithValue - utility (additional option from thunkAPI) that you can return/throw in your action creator to return a rejected response with a defined payload and meta. It will pass whatever value you give it and return it in the payload of the rejected action.
For those that use apisauce (wrapper that uses axios with standardized errors + request/response transforms)
Since apisauce always resolves Promises, you can check !response.ok and handle it with rejectWithValue. (Notice the ! since we want to check if the request is not ok)
export const login = createAsyncThunk(
"auth/login",
async (credentials, { rejectWithValue }) => {
const response = await authAPI.signin(credentials);
if (!response.ok) {
return rejectWithValue(response.data.message);
}
return response.data;
}
);

Redux Saga socket.io

I'm currently developing a chat client which have to be able to receive messages and to send messages. The only problem I'm facing to is that I really don't know how to send messages inside the given component from the Saga example.
I found the example on their API documentation https://redux-saga.js.org/docs/advanced/Channels.html.
Am I be able to reuse the socket const I created inside the watchSocketChannel function? Or do I need to just create the connection twice? What would you advise to do?
import {all, apply, call, fork, put, take} from 'redux-saga/effects'
import {eventChannel} from 'redux-saga';
import * as actions from "../actions";
import io from 'socket.io-client';
function createSocketConnection(url, namespace) {
return io(url + '/' + namespace);
}
function createSocketChannel(socket) {
return eventChannel(emit => {
const eventHandler = (event) => {
emit(event.payload);
};
const errorHandler = (errorEvent) => {
emit(new Error(errorEvent.reason));
};
socket.on('message', eventHandler);
socket.on('error', errorHandler);
const unsubscribe = () => {
socket.off('message', eventHandler);
};
return unsubscribe;
});
}
function* emitResponse(socket) {
yield apply(socket, socket.emit, ['message received']);
}
function* writeSocket(socket) {
while (true) {
const { eventName, payload } = yield take(actions.WEBSOCKET_SEND);
socket.emit(eventName, payload);
}
}
function* watchSocketChannel() {
const socket = yield call(createSocketConnection, 'http://localhost:3000', 'terminal');
const socketChannel = yield call(createSocketChannel, socket);
console.log(socket);
while (true) {
try {
const payload = yield take(socketChannel);
yield put({type: actions.WEBSOCKET_MESSAGE, payload});
yield fork(emitResponse, socket);
} catch (err) {
console.log('socket error: ', err);
}
}
}
export default function* root() {
yield all([
fork(watchSocketChannel),
])
I know that the fork function is attaching the watchSocketChannel function to saga and constantly listening.
I'm not sure I have understood correctly your question... If you're asking how/where to fork the writeSocket saga to allow you to dispatch the actions.WEBSOCKET_SEND) action and have your message sent to the socket:
isn't sufficient to do add a fork in the middle of the socket channel creation?
const socket = yield call(createSocketConnection, 'http://localhost:3000', 'terminal');
fork(writeSocket, socket); // I've added this line
const socketChannel = yield call(createSocketChannel, socket);

Redux await async thunk keeps going

I'm currently using redux / redux-thunk to fetch a user using api-sauce like so
let authToken = await AsyncStorage.getItem('#TSQ:auth_token')
if (authToken) {
store.dispatch(fetchUser(authToken))
console.log('show login screen')
// dont worry, if the token is invalid, just send us to onboarding (api determines this)
loggedInView()
} else {
Onboarding ()
}
....
export const fetchUser = authToken => async dispatch => {
console.log('dispatching auth token')
console.log('here goes request')
let res = await api.get(`/auth/${authToken}`);
if (res.ok) {
console.log('have the user')
dispatch(
setUser(res.data)
)
} else {
dispatch({
type: 'SET_USER_DEFAULT'
})
}
}
When this code is ran, the user is still loading and the console.logs are not in order
`dispatching auth token`
`here goes request`
`show login screen`
Why is this happening?
This is because the actual call to store.dispatch(fetchUser(authToken)) is synchronous - the dispatch() method is not asynchronous, so the logging "show login screen" will occur immediately after execution of the fetchUser() method.
If you want loggedInView() to be executed after a response is returned from your network request (ie the call to the async method api.get()), then you could consider refactoring your code in the following way:
if (authToken) {
store.dispatch(fetchUser(authToken))
// Remove navigation from here
} else {
Onboarding ()
}
And then:
export const fetchUser = authToken => async dispatch => {
console.log('dispatching auth token')
console.log('here goes request')
let res = await api.get(`/auth/${authToken}`);
if (res.ok) {
console.log('have the user')
// Occurs after network request is complete
console.log('show login screen')
// Add navigation here to go to logged in view now that request is complete
loggedInView()
dispatch(
setUser(res.data)
)
} else {
dispatch({
type: 'SET_USER_DEFAULT'
})
}
Hope this helps!

Dispatch Action Inside A Promise Then Function In A Saga

I have a saga (using redux-saga) that calls a function that POSTs to an API endpoint (using axios). The deeper API call through axios returns a promise. I'd like to dispatch actions inside the then() method of the promise, but I obviously can't use a yield. A put() doesn't seem to put anything. What's the right way to do this?
Here's the saga:
export function* loginFlow(action) {
try {
const {username, password} = action.payload;
const responsePromise = yield call(login, {username, password, isRegistering: false});
yield responsePromise
.then(result => {
console.log('loginFlow responsePromise result', result);
put(creators.queueLoginSucceededAction()); // doesn't work
put(push('/')); // doesn't work
})
.catch(err => {
console.log('loginFlow responsePromise err', err);
put(creators.queueLoginFailedAction()); // doesn't work
});
}
catch(err) {
console.log(err);
yield put(creators.queueLoginFailedAction());
}
}
Here's the function being called:
export function* login(options) {
try {
// if we are already logged in, via token in local storage,
// then skip checking against server
if( store.get('token') ) {
return Promise.resolve('Already logged in.');
}
// query server for valid login, returns a JWT token to store
const hash = yield bcrypt.hashSync(options.password, 10);
yield put(creators.queueLoginHttpPostedAction());
return axios.post('/auth/local', {
params: {
username: options.username,
password: hash,
hash: true,
}
})
.then(result => {
console.log('api>auth>login>result', result);
put(creators.queueLoginHttpSucceededAction()); // doesn't work
return Promise.resolve('Login successful');
})
.catch(err => {
console.log('api>auth>login>err', err);
put(creators.queueLoginHttpFailedAction()); // doesn't work
return Promise.reject(err.message);
});
}
catch (err) {
yield put(creators.queueLoginHttpFailedAction());
return Promise.reject('Login could not execute');
}
}
A saga 'yield call' will wait for a returned promise to complete. If it fails, it throws an error, so instead of using 'then' and 'catch' for promises, you can just use a normal try-catch instead.
The Redux Saga docs explain this in more detail - definitely worth a read:
https://redux-saga.js.org/docs/basics/ErrorHandling.html
In other words, the login(options) function below will execute the HTTP request and so long as it doesn't send back a rejected promise, it will continue to queue the succeeded action and redirect the user back. If it does send back a rejected promise, it will instead immediately jump to the 'catch' block instead.
Corrected for the login flow:
export function * loginFlow(action) {
try {
const {username, password} = action.payload;
const responsePromise = yield call(login, {username, password, isRegistering: false});
console.log('loginFlow responsePromise result', result);
yield put(creators.queueLoginSucceededAction());
yield put(push('/'));
}
catch(err) {
console.log('loginFlow responsePromise err', err);
yield put(creators.queueLoginFailedAction());
}
}
And for the actual login process:
export function * login(options) {
// if we are already logged in, via token in local storage,
// then skip checking against server
if( store.get('token') ) {
return Promise.resolve('Already logged in.');
}
// query server for valid login, returns a JWT token to store
const hash = yield bcrypt.hashSync(options.password, 10);
yield put(creators.queueLoginHttpPostedAction());
try {
yield call(
axios.post,
'/auth/local',
{ params: { username: options.username, password: hash, hash: true } }
)
console.log('api>auth>login>result', result);
yield put(creators.queueLoginHttpSucceededAction()); // doesn't work
return Promise.resolve('Login successful');
} catch(err) {
console.log('api>auth>login>err', err);
yield put(creators.queueLoginHttpFailedAction()); // doesn't work
return Promise.reject(err.message);
}
}

Resources