How can I transform enums to object for js?
For example:
type action = Add(int) | Reset | Divide(float)
I need to convert JS object like:
const action = {
type: 'Add',
payload: 10,
}
This needs for redux.
How can I transform enums to object for js?
For example:
type action = Add(int) | Reset | Divide(float)
I need to convert JS object like:
const action = {
type: 'Add',
payload: 10,
}
This needs for redux.
Hi @snatvb it sounds like you are using interop with Redux?
Would something like this work for you?
type action = Add(int) | Reset | Divide(float)
external asJson: 'a => Js.Json.t = "%identity"
let toReduxAction = (action: action) =>
switch action {
| Add(value) => {"type": "Add", "payload": value}->asJson
| Reset => {"type": "Reset"}->asJson
| Divide(value) => {"type": "Divide", "payload": value}->asJson
}
let reduxAction = toReduxAction(Add(10))
// { type: 'Add', payload: 10 }
If your reducer is written in ReScript then you could send a variant as an action.
I can’t (look at redux documentation, that action must be an object and contains “type” field)
Oh yeah. I have used useReducer
and thought redux
would also accept actions as any type.
https://github.com/a-c-sreedhar-reddy/rescript-redux-react/
type _type = Increment | Decrement | Update(int)
type action = {"type": _type}
let reducer = (~state=1, ~action: action) =>
switch action["type"] {
| Increment => state + 1
| Decrement => state - 1
| Update(int) => int
}
Would this work?
Thanks, I’ll check and give feedback to you
So. I thank that type must be a string
, so I did toReduxAction
function what transform re-script action to redux action. Where re-script action is payload.
type reduxAction = {
@as("type") _type: string,
payload: action,
}
let toReduxAction = action => {_type: "ReReduxAction", payload: action}
But I still think that ReScript should have deriver decorator for configure transformation to JS.
Rust has library – serde for serialization. There is good decision for that.