VS code - search for function reference within specific function- macOS - redux

is there any quick way in vs code to search for
method1 referenced inside method2?
I am trying to see if using remote-redux-devtools is useful for my project, and we are using next js which does server side calls via getInitialProps so I am trying to find all references to dispatch inside getInitialProps
rather than search for either term (dispatch or getInitialProps) via command + shift + F individually, i need a more specific search.
in this case I need to search for references to dispatch inside getInitialProps

If we can assume that your getInitialProps functions are of a form similar to this:
static async getInitialProps(ctx) {
const res = await fetch('https://api.github.com/repos/zeit/next.js')
const json = await res.json()
dispatchEvent(event)
return { stars: json.stargazers_count }
}
particularly with respect to the return statement on the final line, then this regex works to distinguish those getInitialProps functions with the sequence dispatch somewhere in that function.
^.*getInitialProps[\s\S]*?\bdispatch[\s\S]*?(return).*\n.*
If you want only dispatch as opposed to dispatchEvent you could use word boundaries around it like \bdispatch\b unless it is used as dispatch( then use \bdispatch( or similar.
See regex101 demo

Related

Sveltekit and SSR

I need a bit of help understanding SSR in the context of sveltekit. I noticed that the load method is called both on the server and the client and I cannot wrap my head around this. I guess it is needed to initialize the state of the client-side component, but why not just pass the props resulting from the SSR to the client?
What if a database request needs to be done during SSR? Now that same database request is repeated from the client? What if that is not even possible? I understand that I can use browser from $app/env to run different code on the server and in the browser but what props do I return? Is there any way to pass data from the server-side invocation of load to the client-side invocation?
why not just pass the props resulting from the SSR to the client?
In order to do this, the props need to be serializable. You couldn't — for example — do something like this:
<script context="module">
export async function load({ fetch }) {
const data = await fetch('/data.json').then(r => r.json());
const model = create_model(data);
return {
props: { model }
};
}
</script>
<script>
export let model;
</script>
<h1>{$model.title}</h1>
Or you might need to dynamically import one component in one case, and a different component in another case, and pass that through as a prop.
There's another disadvantage to serializing the load output (which is what happened with SvelteKit's predecessor, Sapper) — in some cases, you might end up serializing a lot more data than you need to:
<script context="module">
export async function load({ fetch }) {
const compressed = await fetch('/compressed-data.json').then(r => r.json());
const data = decompress(compressed);
return {
props: { data }
};
}
</script>
So SvelteKit runs load on both server and client. But it doesn't mean you're making unnecessary network requests. Anything you fetch in your load function is baked into the server-rendered HTML, meaning a) everything is contained in one request, b) the data used for server and client renders is guaranteed to be consistent, and c) any strings that appear in the fetched data and also appear in the markup are essentially 'free' because of gzip (or brotli).
What if a database request needs to be done during SSR?
You shouldn't be talking directly to the database in load, you should be creating an endpoint and requesting data with fetch. (We may add a method for auto-generating these endpoints in future, but it's not currently on the roadmap.)

Wrap async usage with Meteor

I'm trying to wrap an async function inside my Meteor app.
To make it maximum simple I will try to make a basic example (because all I found was kinda more complex that i actly need).
In my app I am trying to do
console.log("1");
my_func(string_to_display);
console.log("2");
As node is async I get logs 1 and 2 before to see the string i sent to the function.
I tried to call it this way
var my_func_sync = Meteor.wrapAsync(my_fync);
var result = my_func_sync(string_to_display);
Most examples here are more complex, with URLs and calls between server/client/other services. I would like to know if there is a way to wrap a simple function that will only send my string to console. Could anyone give me a most basic example ever please? Would be highly appreciated!
I guess using async await can sort the issue.
async my_funct1(){
console.log("1");
await my_func(string_to_display);
console.log("2");
}
Note that you will need to use async with my_funct1() if you need to use await. This will typically wait for the call to return back from myfunc(string_to_display) to proceed to the next line.

Cloud Functions for Firebase - get parent data from database trigger

Is there a clean built in way of directly referencing the data value of the node above the database trigger? I understand I can get a parent ref which I could then query for the value, but if there was a more concise way of doing this that would be great thanks.
For clarity, I want to use a child node within an object as a trigger, and when it occurs get the value of the parent object directly, to avoid the function being invoked when other changes are made to the parent object like so:
const parentObject = {
triggerValue: 'I want the function to be triggered only on writes to this path',
parentValue: 'But I also want this value',
}
Thanks
I've googled for this answer like six times and keep having to re-implement the solution.
Here's how to get the parent data, post, from a child attribute, post.body, that's changed:
exports.doStuff = functions.database
.ref("/posts/{postId}/body")
.onWrite(event => {
return event.data.ref.parent.once("value").then(snap => {
const post = snap.val();
// do stuff with post here
});
});
You can use event.data.ref and event.data.adminRef to navigate the database. They are Reference objects and work exactly like they would if you were building a web app with Firebase on the client side. So, if using the parent property to navigate up a level works fine for you, then just use that. There's no additional special syntax.

Redux Saga async/await pattern

I'm using async/await throughout my codebase. Because of this my api calls are defined by async functions
async function apiFetchFoo {
return await apiCall(...);
}
I would like to call this function from my saga code. It seems like I can not do this:
// Doesn't work
function* fetchFoo(action) {
const results = await apiFetchFoo();
yield put({type: "FOOS_FETCHED_SUCCESSFULLY", foos: results});
}
However, this does work, and matches the redux saga documentation:
// Does work
function* fetchFoo(action) {
const results = yield call(apiFetchFoo);
yield put({type: "FOOS_FETCHED_SUCCESSFULLY", foos: results});
}
Is this the correct way to use Redux Saga alongside async/await? It is standard to use this generator syntax inside of the saga code, and the async/await pattern elsewhere?
Yes, that's the standard way to use Redux-Saga.
You should never be calling the await function directly inside the saga-generator, because redux-saga is for orchestrating the side-effects. Therefore, any time that you want to run a side-effect you should do it by yielding the side-effect through a redux-saga effect (usually: call or fork). If you do it directly without yielding it through a redux-saga effect, then redux-saga won't be able to orchestrate the side-effect.
If you think about it, the redux-saga generator is completely testable without the need of mocking anything. Also, it helps to keep things decoupled: if your apiFetchFoo returned a promise, the saga would still work the same.
As pointed out by Josep, await cannot be used inside a generator. Instead you need to use an async function. Also, note this is a limitation of async function itself. It is not imposed by redux-saga.
Beyond this, I also wanted to mention that it is a conscious choice by the redux-saga authors to not allow devs to express sagas as async/await functions.
Generators are more powerful than async/await and they allow advanced features of redux-saga like co-ordinating parallel tasks.
Moreover, expressing sagas as generators help us define Effects which are plain objects defining the side effect. Effects makes it very easy to test our sagas.
So, although your working code is fine, maybe not mixing up sagas and async function is a good idea.
Just define your apiFetchFoo to return a promise which resolves with the response to the request. And when this happens your saga will resume with the results.
const apiFetchFoo = () =>
fetch('foo')
.then(res => res.json())
As the previous answers says , Redux saga uses side effects which handles the async within it so the way of doing it , Is using yield and call if calling an API and so on so far
await always work within a function that's declared as async. #thumbRule
async function fetchList () {
let resp = await fetchApi([params]);
}

RequireJS loads a .js, but is inline code still async?

From what I have seen using a debugger, calling:
require(["menu/main-menu"], function(util) {
Will load the main-menu.js file, but the function is called before the global code in the required .js file is executed? Is this correct?
If so, what is the best way to have all that code executed before my function is called?
The problem I am trying to solve is I want the code in mani-menu.js to all be in a module. But I can't call any method in that module until the global code in there is executed which creates the module.
I can call a global method in there which then creates everything, but that then requires a global init() method in every .js file (each with a unique name).
What's the best way to handle all this?
Update: There's a more basic question here (maybe). In writing javascript (and I use Sencha Ext JS & TypeScript), I need to create my objects. So when I go to create say my main menu, I want to call a method in my main-menu.js file to get that Ext JS derived menu object I created.
I think all the code in main-menu.js should be in a namespace, including the method I call to get the menu object. Is that correct? In addition, the way most Ext JS code is set up is you have several Ext.define() calls as well as other variable instantiations, and then the function that takes all that, builds the full menu, and returns it. But that requires all that code has executed in main-menu.js before I call it.
Am I approaching this correctly? My experience to date is Java & C# and I may be trying to fit that model incorrectly to javascript.
Let's suppose menu/main-menu.js contains this:
define(function () {
// Module factory function
return [... whatever you want to expose...];
});
And your application does this:
require(["menu/main-menu"], function (util) {
// Require callback.
});
What happens is:
The require call loads menu/main-menu.js.
The define in menu/main-menu.js is executed.
The module factory function (the function passed to define) is executed.
The require callback is executed with the symbol util set to
what the factory function in menu/main-menu.js returned.
As for simulating namespaces, there are multiple ways to do it. For
instance, you can do it like this:
define(function () {
return {
foo: function () {},
bar: function () {},
[...]
};
});
This exports an object with two functions in it. You can then use it
like this:
require(["menu/main-menu"], function (util) {
util.foo();
util.bar();
});
RequireJS also supports a CommonJS-style of defining modules:
define(function (require, exports, module) {
exports.foo = function () {};
exports.bar = function () {};
[...]
});
This is functionally equivalent to the first way I defined the module
earlier: you get the same two functions and you use them in the same
way as I've shown above.
Unfortunately, I can't speak about Ext JS specifically because I don't
use it.

Resources