I am using rollup in a NodeJS process. It works but I'm wondering about an output
async function build(foo) {
try {
const bundle = await rollup.rollup(rollupConfig.inputOptions);
const whatever = await bundle.write(rollupConfig.outputOptions);
return whatever
}
catch(err) {
console.error('error:', err)
}
}
The files are written correctly, but whatever is undefined. Should it be something?
If there is an error then the catch works ok
Related
I tried creating a custom plugin to download data from backend using i18next plugin, however, is stuck at data dumping process. I am using NextJS for frontend.
Here is the configuration file for NextJS.
const { i18n } = require('./next-i18next.config.js/index.js')
module.exports = {
reactStrictMode: true,
i18n
}
Here is the next-18next.config.js file content.
const getDefault = ()=>{
return {
parse: data => JSON.parse(data),
addPath: '/locales/{{lng}}/{{ns}}',
}
}
class Backend {
constructor(services, backendOptions, i18nextOptions){
this.init(services,backendOptions,i18nextOptions)
}
init (services,options={},allOptions={}){
this.services = services;
this.options = {...getDefault(),...options};
this.allOptions = allOptions;
}
async read(language, namespace, callback) {
const payloadUrl = this.options.payloadUrl;
this.data = null;
try {
const response = await fetch(payloadUrl);
const payloadData = await response.json();
this.data = payloadData;
}
catch(err){
return callback(err,this.data)
}
this.loadUrl(language,namespace,callback);
}
async loadUrl (language,namespace,callback){
const loadPath = this.options.loadPath;
const url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace});
try {
const response = await fetch(url);
const data = await response.json();
return callback(language,namespace,data)
}
catch(err){
console.log("Error while fetching payload ", err)
callback(err,null)
}
}
save (language, namespace, data) {
console.log(language,namespace,data);
}
create (language, namespace, key, fallbackValue) {
console.log(language,namespace,key,fallbackValue)
}
dumpData(language,namespace,data){
const filePath = this.services.interpolator.interpolate(this.options.addPath, { lng: language, ns: namespace});
// need to find a way to dump the file into the given filePath, (right now
// I cannot find proper way to use fs library)
console.log(filePath, "is the file path")
console.log("data we dumping ", data);
}
}
Backend.type = "backend";
module.exports = Backend;
I am following https://github.com/i18next/i18next-http-backend and have no idea how they are dumping the payload we get from backend to specific folder. I tried doing it manually adding fs library, however we are using NextJS and using fs gives me error Can't resolve 'fs'. How can we dump the data we receive from backend into its required location?
The callback signature is wrong, callback(language,namespace,data) is not correct. The signature should be callback(error, result) => this means you may change it to: callback(null, data)
Additionally, all these are not async functions, plain old callback based functions, like described here: https://www.i18next.com/misc/creating-own-plugins#backend
btw: if you're fetching data from your backend, why do you not simply use i18next-http-backend and adapt the loadPath and or the parse option and/or the request option: https://github.com/i18next/i18next-http-backend#backend-options ?
const accounts = await web3.eth.getAccounts();
App = {
load: async () => {
await App.loadWeb3(
await App.loadAccount()
)
},
loadWeb3: async () => {
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider
web3 = new Web3(web3.currentProvider)
} else {
window.alert("Please connect to Metamask.")
}
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(ethereum)
try {
// Request account access if needed
await ethereum.enable()
// Acccounts now exposed
web3.eth.sendTransaction({/* ... */})
} catch (error) {
// User denied account access...
}
}
// Legacy dapp browsers...
else if (window.web3) {
App.web3Provider = web3.currentProvider
window.web3 = new Web3(web3.currentProvider)
// Acccounts always exposed
web3.eth.sendTransaction({/* ... */})
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
}
},
loadAccount: async () => {
App.account = web3.eth.accounts[0]
console.log(App.account)
}
}
$(() => {
$(window).load(() => {
App.load()
})
})
The error is in LINE 1 where I get the accounts from Ganache but await is valid only for async.
What changes should I make in this code to remove the error? Please help me.
If I remove this line the error says that it cannot access accounts and after this await does not work.
Is there any way to make this piece of code in the form of an ASYNC function?
await calls can only be made in functions marked as async. As you have used await in line 1 it is not wrapped in an async function. You can wrap your code in a async function and then call that function. e.g something like:
const main = async () => { // <- the async wrapper function
const accounts = await web3.eth.getAccounts();
// .... rest of your code
$(() => {
$(window).load(() => {
App.load()
})
})
}
main()
Or if you want to be more advanced and not save the function at all
(async ()=>{
const accounts = await web3.eth.getAccounts();
// .... rest of your code
})() // <- call the function right after declaring it
I'm new to next js. And I have one user.js file inside of my pages directory in next.js. This is the source code:
// pages/user.js
function user(props) {
const [userList, setUserList] = useState([])
const [roleList, setRoleList] = useState([])
async function initialFetch() {
const userList = await fetch('GET', GET_ALL_USERS)
setUserList(userList)
const roleList = await fetch('GET', GET_ALL_ROLES)
setRoleList(roleList)
console.log('userList in async')
console.log(userList)
}
if (!props.userList.status) {
initialFetch()
} else {
setUserList(props.userList)
setRoleList(props.roleList)
}
console.log('userList outside')
console.log(userList)
return (
<>
<TableUserManagement users={userList} roles={roleList}/>
</>
)
};
user.getInitialProps = async (ctx) => {
const userList = await fetch('GET', GET_ALL_USERS)
const roleList = await fetch('GET', GET_ALL_ROLES)
return {userList, roleList}
}
The problem is that above async initialFetch() function is always called uninfinitively :
So what am I doing wrong here? Thank you
Note: I have tried to use useEffect() but the looping still happening. This the code :
useEffect(
() => {
if (!props.userList.status) {
initialFetch()
} else {
setUserList(props.userList)
setRoleList(props.roleList)
}
console.log('user list diliuar')
console.log(userList)
}
)
This issue is not related to Next.js but React itself. This is the code that cause unfinite calls:
if (!props.userList.status) {
initialFetch()
} else {
setUserList(props.userList)
setRoleList(props.roleList)
}
Since after setting any state, your component re-renders and that part of code keeps running again, and the fetch cause setting state again,... that loops forever.
You should move you data-fetching logic in side componentDidMount or useEffect. Remember to provide the dependency array of useEffect. In this case, you may only need to fetch data only once so you should provide the empty dependency array.
useEffect(() => {
async function initialFetch() {
const userList = await fetch('GET', GET_ALL_USERS)
setUserList(userList)
const roleList = await fetch('GET', GET_ALL_ROLES)
setRoleList(roleList)
}
if (!props.userList.status) {
initialFetch()
} else {
setUserList(props.userList)
setRoleList(props.roleList)
}
}, []);
P/s: you should name you React component in PascalCase (ex: User)
I know there are many people with this same problem but ive tried them all and havent been able to achieve the following.
I have the following function
let { exec, spawn } = require('child_process');
export const buildServer = async (silent?) => {
try {
const child = spawn('ng run boilerplate:server:production;', []);
child.on('exit', (code) => {
console.log(`Child process exited with code ${code}`);
});
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
} catch (error) { throw error; }
}
This is the basic implementation of spawn. Here is the error I get
Error: spawn ng run boilerplate:server:production; ENOENT
How can i run that command (ng ...) without buffering the output?
are there any alternatives you know of?
I finally bumped in to this article https://medium.com/edge-coders/node-js-child-processes-everything-you-need-to-know-e69498fe970a
now my function works like this.
export const stream = async (cmd: string, silent?) => {
if (!silent) { console.log("[running] ".gray, `${cmd}`.green.bold); }
try {
const child = spawn(cmd, {
stdio: 'inherit',
shell: true
});
} catch (error) { throw error; }
}
i'm new to redux/react and trying to put together a login page. But for some reason the code within the async parameters are not running. I was trying to write it so that I don't need to put in a bunch of .then statements. My code is below.
export function signIn (email, password) {
console.log('trying to login');
return async function (dispatch) {
const error = validateCredentials(email, password);
if (error) {
return error;
}
try {
console.log('gather credentials');
const geoipjson = await geoip();
console.log(geoipjson);
const ip = geoipjson.ip;
console.log(ip);
const country = geoipjson.country_name;
console.log(country);
const fp = await getFingerprint();
console.log(fp);
const res = await authenticateUser(email, password, ip, country, fp);
if (!res.jwt) {
return res;
}
const update_error = await updateLoginStamp(res.jwt);
if (update_error) {
return update_error;
}
setCookie("jwt", res.jwt);
console.log('user authenticated');
dispatch({type: USER_AUTHENTICATED});
history.push('/');
return null;
} catch (error) {
console.log('authentication error');
dispatch({type: AUTHENTICATION_ERROR, error});
return error;
}
}
Is it logging an error at the beginning? Also, can you post the validateCredentials code?
const error = validateCredentials(email, password);
if (error) {
console.log('Error: ', error);
return error;
}
Actually, I figured out the solution with some help from a blog entry. I realized the code after,
return async function (dispatch) { ... }
wasn't being called. I was calling this function from the main app.js, but needed to "dispatch" from the component making the call, to make use of the middleware thunk. I didn't understand the whole answer but it has to do with binding to an actioncreator. The blog here handled it pretty nicely, the best solution I could find.
import {connect} from "react-redux";
import {action1, action2} from "myActions";
const MyComponent = (props) => (
<div>
<button onClick={props.action1}>Do first action</button>
<button onClick={props.action2}>Do second action</button>
</div>
)
// Passing an object full of actions will automatically run each action
// through the bindActionCreators utility, and turn them into props
export default connect(null, {action1, action2})(MyComponent);
the full explanation and the blog entry can be found here. This solved a huge problem for me and was done in an excellent way, in my opinion.