ReactJS.net unable to debug - asp.net-core

I've created a small app using ReactJS.Net and ASP.NET 5. If I render a component serverside using #Html.React and tie that to the MVC
#using System.Threading.Tasks
#using React.AspNet
#model Models.DashboardViewModel
#Html.React("MessageBoard", new
{
recentPosts = Model.RecentPosts
})
messageBoard.jsx
"use strict";
var MessageBoard = React.createClass({
render: function(){
return (<table className="table forum table-striped">
<thead>
<tr>
<th className="cell-stat"></th>
<th>Topic</th>
<th className="cell-stat text-center hidden-xs hidden-sm">Replies</th>
<th className="cell-stat-2x hidden-xs hidden-sm">Last Post</th>
</tr>
</thead>
<tbody>
{this.props.recentPosts.map(function(boardPost){
return <BoardPostRow post={boardPost}/>;
}, this)}
</tbody>
</table>)
}
});
This all works great. The problem is that when I go to sources, there is no .js file so I have no way to debug. This is probably ok for some simple read-only elements. But now I want to render some interactive elements that contain state, a form for creating a new Post to the "message board". Here's the code in the same *.cshtml file.
<div id="newPost"></div>
#section scripts
{
<script src="#Url.Content("~/scripts/Components/Board/boardPostForm.jsx")"></script>
<script src="#Url.Content("~/scripts/Components/Common/textInput.jsx")"></script>
<script>React.render(BoardPostForm({}), document.getElementById("newPost"))</script>
#Html.ReactInitJavaScript()
}
The error I get in the console is:
Uncaught SyntaxError: Unexpected token <
textInput.jsx:19 Uncaught SyntaxError: Unexpected token <
(index):69 Uncaught ReferenceError: BoardPostForm is not defined(anonymous function) # (index):69
(index):70 [.NET] Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of MessageBoard. See http://fb.me/react-warning-keys for more information.
(index):71 [.NET] Warning: Unknown DOM property class. Did you mean className?
(index):71 Uncaught ReferenceError: MessageBoard is not defined
It seems an error trying to read the .jsx, because it takes me to the render function when I click on the error. What am I missing here? Maybe I need to do the jsx->js conversion as part of my build process (I am using Gulp) instead of relying on ReactJS.NET?

What happens if you hit /scripts/Components/Board/boardPostForm.jsx in your web browser? It should show the compiled JSX and have some ReactJS.NET info at the top of the file. If it doesn't, make sure the *.jsx handler is configured in your Web.config. It should look something like this:
<add name="ReactJsx" verb="GET" path="*.jsx" type="React.Web.JsxHandlerFactory, React.Web" preCondition="integratedMode" />
What am I missing here? Maybe I need to do the jsx->js conversion as part of my build process (I am using Gulp) instead of relying on ReactJS.NET?
You can use Gulp if you like, up to you. I have a sample here that uses Webpack for bundling, and ReactJS.NET for server-side rendering: https://github.com/reactjs/React.NET/tree/master/src/React.Sample.Webpack

Related

nuxtJS how to make javascript load dynamically by page

I would like to insert this script to nuxtJS project and I want it to load dynamically by page.
<!-- LINE Tag Base Code -->
<!-- Do Not Modify -->
<script>
(function(g,d,o){
g._ltq=g._ltq||[];g._lt=g._lt||function(){g._ltq.push(arguments)};
var h=location.protocol==='https:'?'https://d.line-scdn.net':'http://d.line-cdn.net';
var s=d.createElement('script');s.async=1;
s.src=o||h+'/n/line_tag/public/release/v1/lt.js';
var t=d.getElementsByTagName('script')[0];t.parentNode.insertBefore(s,t);
})(window, document);
_lt('init', {
customerType: 'account',
tagId: 'xxxxx'
});
_lt('send', 'pv', ['xxxxx']);
</script>
<noscript>
<img height="1" width="1" style="display:none"
src="https://tr.line.me/tag.gif?c_t=lap&t_id=xxxxx&e=pv&noscript=1" />
</noscript>
<!-- End LINE Tag Base Code -->
The important thing is tagId: 'xxxxx' this should be change dynamically by page. for example,
wwww.sample.com/shop1 will load tagId: 'shop_tag1'
wwww.sample.com/shop2 will load tagId: 'shop_tag2'
What kind of tracker is this ? If it does not have any way of setting it app-wise, I guess that you need to have a middleware that is running your function and grabbing the dynamic part from each page.
This can be helpful: https://nuxtjs.org/docs/2.x/directory-structure/middleware/
Also, I did found some issues on using a middleware in a layout, but maybe it's just me, if it does work on your side, you could just dump your js there too.

undefined data error on page reload Nuxt.js

I'm currently developing a universal app using Nuxt.js, the data on most of the pages is retrieved from an API using a fetch hook as well as vuex store. I started noticing errors on page reload/refresh and sometimes when I visit a page from the navbar. The page error is:
TypeError: Cannot read property 'data' of undefined
where data is an object retrieved from an API. I have searched around the internet for this and found it has something to do with data not being loaded or page rendering whilst the data is not fully retrieved. i have found a work around by using a v-if on my template to check if the data is set then display the contents. my question is if there is a way to achieve this, i have tried using the async/await keywords but it doesn't help and i feel like the v-if method is not the best way to handle it.
edit: solved by using $fetchState.pending when using fetch()
If in your template you display right away the data you retrieve from the API, then indeed using the v-if is the right way to do.
If you are using the new fetch() hook, then in your template you can use $fetchState.pending to check if the loading has finished, for example:
<div v-if="$fetchState.pending">
<p> Content is loading... </p>
</div>
<div v-else>
<p> Content has loaded! {{data}}</p>
</div>
<script>
export default{
data(){
return{
data: null
}
}
async fetch(){
this.data = await getSomeAPI
}
}
</script>

Using vue.js without NPM or CLI

I'd like to use Vue.js within one page of a large legacy application. The idea is to replace the old JS+jQuery hodge-podge within a single page -- but leave the rest of the app (many other pages) untouched. So, not interested in using NPM, Node, Vue CLI, Webpack, Babel, etc., just yet.
This is a proof-of-concept before we invest in refactoring the entire frontend of the application.
The approach we followed was to include vue.js via as explained here: https://v2.vuejs.org/v2/guide/installation.html#Direct-lt-script-gt-Include in that one page, and the use Vue only within that one page. This is the general page layout:
<html>
<head>
...
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
...
</head>
<body>
<div id="el">
... vue template ...
</div>
<script>
...
var vm = new Vue({
el : '#el',
data : {
config : <% config.json %> // this is server-rendered, using server templating
...
},
...
});
...
</script>
</body>
</html>
The page does work. However, I get the following error/warning within the Vue console:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.
Although I'd rather not, I can certainly move the page-specific JS to its own separate file (and that does eliminate the warning/error). However, I wouldn't be able to set vm.config with server-provided data along with the loaded page by using server-side template, e.g. config : <% config.json %>. I know I could GET it using JS separately, after pageload, via an AJAX call directly from the server, but for practical reasons I'd like to avoid doing that here.
I'd greatly appreciate any suggestions on how to get this to work nicely. I'm also open to other suggestions with regard to this general pattern, that don't involve retooling the front-end just yet.
And perhaps the answer is to ignore the warning, or somehow disable it, given the page does work as intended...
Thank you!
One simple solution here is to write it to the global window object. IIRC SSR frameworks like Angular universal/Nuxt/Next/... all use this approach.
window.__STATE__ = <% config.json %>
In your JS file you can then refer to the window.__STATE__ object.
var vm = new Vue({
el: '#el',
data: {
config: window.__STATE__
}
})
Ofcourse the order is important here:
<body>
<script>
window.__STATE__ = <% config.json %>
</script>
<script src="app.js"></script>
</body>
Grrr, after several days after enduring this error, I discovered this:
<fieldset id="el">
...
<div id="el">
...
</div>
...
</fieldset>
So the issue was repeating #el within same page.
My mistake.
Just wish the error message emitted by Vue had been a bit more useful!
Bottom line: The pattern described in the origional question works just fine without NPM/CLI.

vue: Uncaught TypeError: Cannot read property ... of undefined

I'm using vue#2.1.3 and the vue official webpack template to build an app.
When developing locally, I often see the warning Uncaught TypeError: Cannot read property ... of undefined, but the HTML can be rendered successfully. However, the HTML can't be rendered when it's deployed to Netlify with npm run build command. So I have to treat this warning seriously.
I learned from here that it's because "the data is not complete when the component is rendered, but e.g. loaded from an API." and the solution is to "use v-if to render that part of the template only once the data has been loaded."
There are two questions:
I tried wrap v-if around multiple statements that's generating the warning but personal I think this solution is verbose. Is there a neat approach?
"warnings" in local development turn into "fatal errors"(HTML can't be rendered) in production. How to make them the same? e.g. both of them issue warnings or errors?
Just use v-if on a common parent to all the elements in your template relying on that AJAX call, not around each one.
So instead of something like:
<div>
<h1 v-if="foo.title">{{ foo.title }}</h1>
<p v-if="foo.description">{{ foo.description }}</p>
</div>
Do
<div>
<template v-if="foo">
<h1>{{ foo.title }}</h1>
<p>{{ foo.description }}</p>
</template>
</div>
have you tried to initialize all the data you need? e.g. if you need a b c, you can do:
new Vue({
data: {
a: 1,
b: '',
c: {}
},
created(){
// send a request to get result, and assign the value to a, b, c here
}
})
In this way you wont get any xx is undefined error
Guys are right but I can add something.
If there is possibility that your root element in the condition can be undefined for some reason, it is good practice to use something like that: v-if='rootElement && rootElement.prop'. It will secure you from getting cannot get property prop of undefined as when rootelement is undefined, it will not go further in checking.
2021 vue3
we can use like this
props: {
form: {
type: String,
required: true,
},
setup(props, context) {
console.log(props.form)

IBM MobileFirst SQL Adapter

I want to connect my IBM MobileFirst apps to my database,
I use wampserver (localhost),
username = "root", password ="...", database name = "mydatabase".
In my MobileFirst project, I created a SQL adapter "myAdapter".
Inside the myAdapter.xml, this is the code:
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source name -->
<!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:3306/mydatabase</url>
<user>root</user>
<password></password>
</dataSourceDefinition>
</connectionPolicy>
</connectivity>
<!-- Replace this with appropriate procedures -->
<procedure name="insertMyTable1"/>
Below is myAdapter-impl.js file
var insertMyTable = WL.Server.createSQLStatement(
"IESERT INTO mytable" +
"VALUES (? , ? , ?);");
function insertMyTable1(id, name, age){
return WL.Server.invokeSQLStatement({
preparedStatement : insertMyTable,
parameters : [id, name, age]
});
}
//--------------------------------------
in one of my pages, I have a addData.html file, below is the code:
<html>
<script>
function insertData(){
var id = document.getElementById("id").value;
var name = document.getElementById("name").value;
var age = parseInt(document.getElementById("age").value);
WL.Client.invokeProcedure({
adapter : "myAdapter",
procedure : "insertMyTable1",
parameters : [ id, name, age ]
});
}
</script>
<body>
<form action="javascript:insertData();">
<table align="center">
<tr>
<td>Id : </td>
<td><input type="text" id="id"></td>
</tr>
<tr>
<td>Name : </td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age : </td>
<td><input type="text" id="age"></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" style="width:100px;">Add</button>
</td>
</tr>
</table>
</form>
</body>
</html>
But I fail to insert the data into mydatabase->mytable, anyone know why ??
error log (in my addData.html)
Uncaught ReferenceError: WL is not defined
This question is completely unrelated to your SQL adapter.
The problem here is that you have used a href to navigate to another HTML file. By doing so you have exited the scope, or context, of the MFP framework, which is why you are unable to use MFP API methods such as WL.Client.invokeProcedure.
A MFP Hybrid application is a Single Page Application. In the app's index.html there are references to the MFP JavaScript framework in order to load it... Without these, things will break.
In order to use multiple "pages" in your application, see the following tutorial:
Building a multi-page application
You must never actually navigate away from the context of the framework, so operations such as a href are not allowed.
If you want to separate your "pages" to separate HTML files, you can see this example project using jQuery Mobile. Other UI frameworks such as Dojo also provide their own implementation for multi-page support which you could use in your MFP application.
Related questions: https://stackoverflow.com/search?q=%5Bworklight%5D+multipage+is%3Aquestion