Trouble with using sockend with cote - cote

I have conversion service from README, little edited
const cote = require('cote')
const responder = new cote.Responder({
name: 'currency conversion responder',
key: 'conversion',
respondsTo: ['convert']
})
const subscriber = new cote.Subscriber({ name: 'arbitration subscriber' })
const rates = { usd_eur: 0.91, eur_usd: 1.10 }
subscriber.on('rate updated', (update) => {
rates[update.currencies] = update.rate
})
responder.on('convert', (req, cb) => {
console.log(`Request: ${JSON.parse(req)}`)
const convertedRate = req.amount * rates[`${req.from}_${req.to}`]
cb(null, `${req.amount} ${req.from} => ${convertedRate} ${req.to}`)
})
and I created sockend.js
const cote = require('cote')
const app = require('http').createServer()
const io = require('socket.io').listen(app)
io.on('connection', (socket) => {
socket.join('room1')
})
app.listen(5555)
const sockend = new cote.Sockend(io, {
name: 'Sockend'
// key: 'a certain key'
})
Now I try to connect to sockend with socket.io client
const Io = require('socket.io-client')
// const socket = Io.connect('http://localhost:8080');
const url = 'http://127.0.0.1:5555/'
const socket = Io.connect(url)
const request = { type: 'convert', from: 'usd', to: 'eur', amount: 100 }
socket.on('connect', async () => {
console.log(socket.connected) // true
socket.emit('convert', request, function (data) {
console.log(`sockend response ${JSON.parse(data)}`)
})
})
But I never get convert request in my conversion-service responder.
What am I missing?

Your Sockend and your Responder key differ. They are not connected to each other. You need to either omit the key property in your Responder and get it picked up by a Sockend without a key on the same network. Or you make it equal to the key in your Sockend. Both of these work:
const responder = new cote.Responder({
name: 'currency conversion responder',
key: 'conversion',
respondsTo: ['convert']
})
const sockend = new cote.Sockend(io, {
name: 'Sockend',
key: 'conversion'
})
or
const responder = new cote.Responder({
name: 'currency conversion responder',
respondsTo: ['convert']
})
const sockend = new cote.Sockend(io, {
name: 'Sockend'
})

Related

Unexpected mutation in pinia prop when change local component reactive()

When the value of an reactive object is changed, a prop in my Pinia store is mutated. I tried different ways of attributing new value to this store to avoid this problem, but so far I dont't really understand what is happenning. This is my code:
Component
const form = reactive({
name: "",
exercises: [{ exercise: "", method: "", series: "" }],
});
const handleChange = ({ value, name }: any, eventIndex: any) => {
const newEx = form.exercises.map((ex, index) => ({
...ex,
...(index === eventIndex ? { [name]: value } : null),
}));
const newForm = { name: form.name, exercises: newEx };
Object.assign(form, newForm)
};
const onSubmit = async () => {
const { valid } = await formRef.value.validate();
if (!valid) return;
const storeTraining = workoutStore.newWorkout.training || [];
const workout = {
...workoutStore.newWorkout,
training: [...storeTraining, form],
};
workoutStore.setNewWorkout(workout);
isOpen.value = false;
};
Store
import { ref, computed } from "vue";
import { defineStore } from "pinia";
import type { IUser } from "#/domain/users/type";
import type { ITraining, IWorkout } from "#/domain/workouts/types";
export const useWorkoutStore = defineStore("workouts", () => {
const creatingWorkoutStudent = ref<IUser | null>(null);
const newWorkout = ref<Partial<IWorkout>>({});
const setCreatingWorkoutStudent = (newUser: IUser) => {
creatingWorkoutStudent.value = newUser;
};
const setNewWorkout = (workout: Partial<IWorkout>) => {
newWorkout.value = { ...workout };
return newWorkout.value;
};
const addNewTraining = (training: ITraining) => {
newWorkout.value.training
? newWorkout.value.training.push(training)
: (newWorkout.value.training = [training]);
};
const reset = () => {
newWorkout.value = {};
creatingWorkoutStudent.value = null;
};
return {
creatingWorkoutStudent,
setCreatingWorkoutStudent,
newWorkout,
setNewWorkout,
reset,
addNewTraining,
};
});
And this is a example of an input that mutates reactive values
<text-field
label="Exercício"
#input="
handleChange(
{ value: $event.target.value, name: 'exercise' },
index
)
"
:value="exercise.exercise"
:rules="[validationRules.required]"
/>
Every time that a input changes a value in const form = reactive(), the same property in Pinia store is changed too.
I've created a fiddle to exemplify my issue here

I cannot understand WHY I cannot change state in Redux slice

I get the array of objects coming from backend, I get it with socket.io-client. Here we go!
//App.js
import Tickers from "./Components/TickersBoard";
import { actions as tickerActions } from "./slices/tickersSlice.js";
const socket = io.connect("http://localhost:4000");
function App() {
const dispatch = useDispatch();
useEffect(() => {
socket.on("connect", () => {
socket.emit("start");
socket.on("ticker", (quotes) => {
dispatch(tickerActions.setTickers(quotes));
});
});
}, [dispatch]);
After dispatching this array goes to Action called setTickers in the slice.
//slice.js
const tickersAdapter = createEntityAdapter();
const initialState = tickersAdapter.getInitialState();
const tickersSlice = createSlice({
name: "tickers",
initialState,
reducers: {
setTickers(state, { payload }) {
payload.forEach((ticker) => {
const tickerName = ticker.ticker;
const {
price,
exchange,
change,
change_percent,
dividend,
yeild,
last_trade_time,
} = ticker;
state.ids.push(tickerName);
const setStatus = () => {
if (ticker.yeild > state.entities[tickerName].yeild) {
return "rising";
} else if (ticker.yeild < state.entities[tickerName].yeild) {
return "falling";
} else return "noChange";
};
state.entities[tickerName] = {
status: setStatus(),
price,
exchange,
change,
change_percent,
dividend,
yeild,
last_trade_time,
};
return state;
});
return state;
},
},
});
But the state doesn't change. I tried to log state at the beginning, it's empty. After that I tried to log payload - it's ok, information is coming to action. I tried even to do so:
setTickers(state, { payload }) {
state = "debag";
console.log(state);
and I get such a stack of logs in console:
debug
debug
debug
3 debug
2 debug
and so on.

Redux State is set also to other State that is not Related

Programming is weird, if you think not then check this case 🤣, I'm using createSlices as Redux and I have two slices with their own states.
First one is orderSlice:
export const orderSlice = createSlice({
name: 'order',
initialState: {
order: null,
message: null,
isLoading: true,
}
})
While the second slice is ordersSlice:
export const orderSlice = createSlice({
name: 'orders',
initialState: {
orders: null,
message: null,
isLoading: true,
}
})
And I have this method to fetch the order and the fulfilled phase where the state is set from:
Fetching the order:
export const fetchOrder = createAsyncThunk('', async ({ token, id }) => {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
};
try {
const response = await fetch(`${api}/orders/view/${id}`, requestOptions);
const data = await response.json();
return data;
} catch (error) {
console.log(error);
}
});
Filling the order state:
extraReducers: {
[fetchOrder.fulfilled]: (state, action) => {
state.order = action.payload.data;
state.message = 'Succesfully fetched the Order.';
state.isLoading = false;
}
}
While here is method for fetching the orders:
export const fetchAllOrders = createAsyncThunk('', async (token) => {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
};
try {
const response = await fetch(`${api}/orders/all`, requestOptions);
const data = await response.json();
return data;
} catch (error) {
console.log(error);
}
});
And here updating the orders state:
extraReducers: {
[fetchAllOrders.fulfilled]: (state, action) => {
state.orders = action.payload.data;
state.message = 'Succesfully fetched all Orders.';
state.isLoading = false;
}
}
So the case is that I'm calling the fetchAllOrders in the Order page with UseEffect, here is how:
import { fetchAllOrders } from '../redux/ordersSlice';
useEffect(() => dispatch(fetchAllOrders(user.token)), [user]);
So this is how i run the method to fetch orders with dispatch and it works. But the problem is that when I run this function beside the orders state that is filled with the same data, also the order state is filled with the same data and this is impossible as I've cheked all the cases where I could misstyped a user,users typo but there is none I found, and I don't know.
And here is the store:
import orderSlice from './redux/orderSlice';
import ordersSlice from './redux/ordersSlice';
const store = configureStore({
reducer: {
order: orderSlice,
orders: ordersSlice
},
});
You have to give your thunks an unique name: If you name both '' they will be handled interchangably.
Also, you should be using the builder notation for extraReducers. We will deprecate the object notation you are using soon.

Use one filfilled for several createAsyncThunk functions

I have two createAsyncThunk - signIn and signUp is it possible to use one fulfilled reducer both? The reason is that fulfilled reducer same for signIn and signUp. Example:
extraReducers: (builder) => {
builder.addCase(signInUser.fulfilled, (state, { payload }) => {
state.isPending = false;
state.email = payload.username;
state.username = payload.username;
state.first_name = payload.first_name;
state.last_name = payload.last_name;
state.title = payload.title;
state.organization = payload.organization;
state.isNew = payload.isNew;
state.isPremium = payload.isPremium;
state.id = payload.id;
state.error = '';
state.access_token = payload.access_token;
localStorage.setItem(REFRESH_TOKEN, payload.refresh_token);
});
}
Yes, have utils for this purpose: watch this
There is an obvious solution that I found after refactoring, you can pass state and payload to another function and it can set state as it would in yourAsyncThunk.fulfilled. Example:
builder.addCase(signInUser.fulfilled, (state, { payload }) => {
assignStateWithUser(state, payload);
});
builder.addCase(signUpUser.fulfilled, (state, { payload }) => {
assignStateWithUser(state, payload);
});
builder.addCase(loadUser.fulfilled, (state, { payload }) => {
assignStateWithUser(state, payload);
});
const assignStateWithUser = (state: initialStateUser, payload: User) => {
state.email = payload.username;
state.username = payload.username;
state.first_name = payload.first_name;
state.last_name = payload.last_name;
state.title = payload.title;
state.organization = payload.organization;
};
Types for state and payload:
type initialStateUser = RequestPending & { error: string } & User;
export interface User {
id: number;
username: string;
first_name: string;
last_name: string;
email: string;
title: string;
organization: string;
};

Redux toolkit - Cannot use 'in' operator error on upsertMany

I am following the docs to upsertMany into my redux createSlice.
I am following this part of the docs.
I keep getting this error in my upsertMany call. Why is this?
Unhandled Rejection (TypeError): Cannot use 'in' operator to search for '525' in undefined
I have noticed that normalizr returns both entities and result objects, however, RTK only uses entities. Where do we use the result if we need to at all?
Here is my createSlice
const posts = new schema.Entity('actionPosts', {}, { idAttribute: 'id' })
export const fetchPosts = createAsyncThunk(
'actionPosts/fetchPosts',
async (email) => {
const { data } = await getUserActionPostsByUser({ email })
const extractedPosts = data.userActionPostsByUser
const normalizedData = normalize(extractedPosts, [posts])
return normalizedData.entities
}
)
const adapter = createEntityAdapter({
sortComparer: (a, b) => b.createdAt.localeCompare(a.createdAt),
loading: '',
error: '',
})
const initialState = adapter.getInitialState()
const slice = createSlice({
name: 'actionPosts',
initialState,
extraReducers: {
[fetchPosts.fulfilled]: (state, { payload }) => {
console.log('payload', payload.actionPosts)
adapter.upsertMany(state, payload.actionPosts) // error happens here
},
},
})
export default slice.reducer
Here is the normalized object
{
actionPosts: {
525: {
id: 525
email: "test#test.com"
content: "lorem ipsum"
createdAt: "2020-09-24T20:29:44.848Z"
}
}
result[
525,
]
}

Resources