Using getInitialProps with an optional Parameter with NextJS - next.js

I have a page which allows a user to update a record, lets call it /edit-record, I want to support /edit-record/1 as a route which would load the data (I tried using getInitialProps) but I also want to make it so /edit-record is a page (ideally the same page) but without the API call to fetch the details happening.
So if I pass /edit-record/3 it should fetch record 3, if the url is /edit-record it just awaits user events.
The issue being I tried a conditional in getInitialProps, a if(query.recordId) {} but the else clause returns a null which NextJS doesnt like; it also just feels a bit wrong in terms of the approach.
What is the better way? Ideally I don't want to create two page files to handle the two conditions as all of the logic is the same.

Related

Object storage alternatives in Wordpress

so I am developing a Quiz plugin for Wordpress.
I have defined a shortcode which is replaced by my html, and I also have enqueued javascript and styles. So far all good.
At this point, I want to visualize each question using ajax and jquery. My quiz has some sophisticated logic - some quiz question-trees can fall off depending on the answers and on the settings of the plugin.
Thus, I am trying to achieve a solution, where javascript uses ajax call to fetch one next question at a time. On the backend, I created controller-class which is responsible for handling the logic and outputing the fetched-question's html code. Thus, whenever a starts the quiz, the backend will generate some controller object.
My question is, how can i store multiple controller objects persistently? So that i can get the current use's progress.
To do that, i need some kind of persistent storage for all the running quizzes. Here, as far as I understand, i have 2 alternatives: put serialized controller objects into the database, or use some sort of WP_CACHE.
So now I have some questions:
1) Is there any other alternative for storing a set of objects in Wordpress?
2) Is the approach I am using for the quiz implementation - okay? Like maybe I am doing something unconventional?
3) Is having ajax calls communicating to the DB a good idea?
* Edit *
Thanks to #cabrerahector, who pointed out the set_transient() wordpress API.
I was able to store an object in the db with the following code:
...
$base64_serial = base64_encode(serialize($report_controller));
set_transient($report_id, $base64_serial, 60*60*12);
...
and then retreive the object with the following code:
...
$report_controller = unserialize(base64_decode( get_transient( $_GET['report_id'] )));
...
I know it's kind of hacky, but does anybody know a better way? Please don't tell me to create an array with all fields of the class...

Algolia - WordPress - how can I get the actual query into JS variable to work with it further in the hits template?

I would like to do some interesting stuff with the hits that are being displayed based on the search query that user is not only typing into search box but actually filtering using the instant search filters. I have filter based on hierarchical events_location taxonomy. Based on what user selected I would get the info in JS variable that I can then further use to do other operations in the hits div, specifically on each hit card.
So my URL when searching updates like this:
/what-to-see/?q=&idx=sdbeta_posts_events&p=0&hFR%5Btaxonomies_hierarchical.events_calendar.lvl0%5D%5B0%5D=JUL%204&hFR%5Btaxonomies_hierarchical.events_category.lvl0%5D%5B0%5D=All&hFR%5Btaxonomies_hierarchical.events_locations.lvl0%5D%5B0%5D=Paddock%20Stage
I could potentially take the URL and extract the data from it, but I am sure there is more elegant way of working with the query.
In InstantSearch.js, the state is managed by another library called the algoliasearch-helper. Through this library you can read and write the search parameters.
The cleanest to access the helper is to build a custom widget, which is a plain object with lifecycle hooks (initial rendering and the other renderings). You can read more about custom widgets there.
Once you've accessed the helper, you can read and write with the helper API.
This can be found under search.searchParameters
So:
console.log(search.searchParameters);
Will give you whole object that you can then work with.
There is however one issue with this and that is that it works only on initial load. I was unable to make this work or get any data after starting to selecting categories. So if anyone knows how to use this so it updates after each selection please comment bellow.

Meteor collection returns no results except in template

I'm new to the Meteor framework, and am having problems accessing data from my collection, outside of a template.
I have a small mongo collection and can retrieve and present its data without problems by using a template. However, when I try to get a cursor or array to use more directly, I get no results returned.
In my script, using find
var dataFind = Fakedata.find();
console.log(dataFind);
console.log(dataFind.count());
gives a cursor object, but a count of zero.
var dataFetch = Fakedata.find().fetch();
console.log(dataFetch);
console.log(dataFetch.length);
gives an empty array, length of zero.
Using the same find() or fetch() from the JS console gives populated objects as I would expect the code above to do. Within a meteor template, everything seems to work fine as well, so the pub/sub seems to be correct.
Any clues as to what I'm doing wrong here?
It looks like your subscriptions aren't ready at the time you try to access your collection data, this is a common gotcha.
When you access your collection data via templates, it is most likely via the use of template helpers which happen to be reactive, so they will rerun when your collections are ready thus displaying the correct data.
When accessing your collections in a non-reactive script though, they will appear empty if the subscription is not yet ready.
You can try using this pattern in your script to execute code only when the subscription is ready :
Meteor.subscribe("mySubscription",function(){
// we are inside the ready callback here so collection date is available
console.log(Fakedata.find().fetch());
});
If you are looking for a more robust approach, try looking at iron:router waitOn mechanism.

Pass data in DurandalJS to other view

I'm developing a SPA webapplication with DurandalJS, but I don't understand something.
Let's say I have page 1 and 2. On page 1 there is a modal that creates a entity in the database with BreezeJS and gives back a key (that was generated in the database).
I want to pass this fetched key and then go to my second page, page 2. I know how I can do this when I put it in the url
http://localhost:60312/#/page2?orderid=2&repairorder=2
But this is not the way for Durandal, or is it? A user can enter a number of his own with al consequences!
How can I solve this?
I would like to add something to the very good #Joseph Gabriel answer. In durandal you can do this:
router.map( url: 'page2/:orderid/:repairorder',
name: 'Page2',
moduleId: 'viewModels/page2');
http://localhost:60312/#/page/2/2
But also, you can do this:
router.map( url: 'page2',
name: 'Page2',
moduleId: 'viewModels/page2');
http://localhost:60312/#/page2?orderid=2&repairorder=2
You don't nedd to specify all the parameters that you are pasing. Yo can get this parameters from the input of the active method.
var activate = function(context) {
console.log(context.orderid);
console.log(context.repairorder);
}
Sometimes the second solution can be more appropriated if you want that the user can store the url to repeat a query only copping that in the browser.
As far as I know, the only seamless way to pass parameters between view models in a Durandal app is to use the normal hash-based url parameters.
In you example, you can define a router that takes a orderId and repairOrder parameters, then your url would look something like this: http://localhost:60312/#/page/2/2
This is best option, if your data isn't too sensitive. Leave the navigation parameters in the open, and handle the values with care in the second view model. In other words, design your view model so that it can properly handle any values - even if a user directly modifies a parameter value, your view model should be able to handle it correctly.
It can be advantageous to be able to set url parameters directly, but you do have to be careful to ensure the integrity of the values before consuming them.
However, if you need to hide the parameters, you do have some different options:
Encryption: Use an encryption library like tea.js, and encrypt the value before adding it as a parameter value for navigation. Then, of course, decrypt it on the second page before using it. This allows Durandal's router navigation to work normally, while preventing users from supply their own values.
If you really need to prevent users from entering their own values, and you can bear the overhead of a few extra KB's, this is a good approach as long as you only need to pass a few parameters.
Shared data model: Use a singleton model which is shared between the two view models. This model can be manually required() as needed, and essentially serves as a repository for the application state that is shared between one or more view models.
This works fine, but it's kind of like having a big global variable - it can get messy if it's overused.
Modify VM directly: (Only for singleton view models)
Manually require() the second view model and set its properties before navigating to it.

How do I display data from an external database in Drupal?

I am building a custom module that will allow my users to do a simple query against an MS SQL database. I've built the form using hook_form() and have gotten validation to work.
I'm planning on retrieving the data from hook_form_submit(), but once I've done that, how do I append it below the form? It does not appear that I have access to $output from hook_form_submit(). I'm at a loss as to what to do next.
Thanks
Dana
When you are rendering the form you should check for $form_state['values'] to see if the user has already submitted a form when you're rendering the form. Then you could paint the form results in the same step as painting the form.
The first time the user loads the form page the $form_state variable won't contain any submitted form info so you can render an empty results table.
There's a good illustration of the Drupal Form API workflow on Drupal.org here: Form API Internal Workflow Illustration
The problem in trying to output data in the hook_form() method is that the method gets invoked twice which clears the post values the second time through. Throw a dpm($form_state) in the hook_form() function and you'll see two sets of post data. One with values and one without.
So after dissecting the built in Search module, which pretty much operates exactly the way I want my form to work, I figured out how this is done. Well, at least one way you can do it.
What Search module does is take the values from $form_state in hook_form_submit() and pastes them into the URL, then it sets the $form_state['redirect'] to that new URL, effectively storing those variables in the URL and changing the POST to a GET.
Now, in the callback, they extract those values from the URL, do the search on them, THEN they call drupal_get_form(), append the results to the end and return it.
There's another solution HERE where they use SESSION to store the values until the second trip through. Weird, but it works.

Resources