S
SolidJS4mo ago
hannus

Modifying Signals Returned by createAsync in SolidJS: Best Practices and Alternatives

In SolidJS (using the SolidStart framework), how can I modify the signal returned by createAsync? For example, in a scenario where I use createAsync to fetch data from an API and load it into an editor or textarea, then after making modifications, I want to save the updates via an Action by calling another API. The parameter passed to the Action would be the modified data based on what was initially fetched by createAsync. I checked the documentation but couldn’t find a way to modify the signal from createAsync. So I came up with two possible solutions: 1. Use createResource; 2. Create another signal B, then use onMount to set signal B based on the final value of the signal from createAsync. To ensure that signal B is only set after the createAsync value is resolved, the current component would be wrapped in a Suspense component, ensuring other parts are rendered only after the async data is loaded. Is my approach correct? Additionally, the documentation mentions that createAsync is a lightweight version of createResource and will become a primitive in Solid 2.0. Does this mean that createAsync is more recommended for use? thanks
3 Replies
Madaxen86
Madaxen864mo ago
The createAsync way would be: 1. wrap the getter function in cache with a key e.g. 'getEditorData' 2. update the data in the db via action and return json({message:"Updated editor"},{revalidate:"getEditorData"}) -> will revalidate the cache for the getter function and you the createAsync is updated to the latest data. if you want to go the route of optimistic updates, you should probaly use a package like tanstack/query or use the createResource mutate function.
hannus
hannusOP4mo ago
thanks. My understanding is that the value returned by createAsync is a signal, and if I want to modify it, based on the principle of unidirectional data flow, the best practice is to notify its data source that the data has been updated. Specifically, this can be done by using an Action to modify the data source. Once the data source is updated, the signal value obtained by createAsync will automatically be updated accordingly. Is my understanding correct?
Madaxen86
Madaxen864mo ago
Exactly.
Want results from more Discord servers?
Add your server