Can someone provide an example on how to use the library ?
https://www.npmjs.com/package/#ledgerhq/logs
This is my code:
const LedgerWalletProvider = require('#ledgerhq/web3-subprovider');
const createLedgerSubprovider = LedgerWalletProvider.default;
const TransportNodeHid = require('#ledgerhq/hw-transport-node-hid').default;
const ProviderEngine = require('web3-provider-engine');
const RpcSubprovider = require('web3-provider-engine/subproviders/rpc');
const engine = new ProviderEngine();
const getTransport = () => TransportNodeHid.create();
const ledger = createLedgerSubprovider(getTransport, { askConfirm: true });
engine.addProvider(ledger);
engine.addProvider(new RpcSubprovider({ rpcUrl: process.env.BLOCKCHAIN_NODE_MAINNET }));
engine.start();
module.exports = engine;
const logger = require("#ledgerhq/logs");
logger.listen(log => console.log(log.type + ": " + log.message));
Related
I'm trying to export my table to an excel file
, so I created a function after fetching my data that convert from array to excel, I worked but it does not export all data
this is an example of what am getting
here
so as you can see the last three columns are empty, I think the problem is that the date is array data , but I don't know-how
this is my code :
import {
GridToolbarContainer,
gridVisibleSortedRowIdsSelector,
gridFilteredSortedRowIdsSelector,
gridVisibleColumnFieldsSelector
} from "#mui/x-data-grid";
const CustomToolbar = () => {
const apiRef = useGridApiContext();
const getFilteredRows = ({ apiRef }) => gridVisibleSortedRowIdsSelector(apiRef);
const handleExport = (options) => apiRef.current.exportDataAsCsv(options);
const fileType = "application/vnd.ms-excel;charset=utf-8";
const fileExtension = ".xlsx";
const fileName = "myfile";
const buttonBaseProps = {
color: "primary",
size: "small",
};
// const arrayToExcel = (a) => {}
const Export = (a, fileName) => {
const ws = XLSX.utils.json_to_sheet(a);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
const myfiltredRows = (a) => {
const filteredSortedRowIds = gridFilteredSortedRowIdsSelector(apiRef);
const visibleColumnsField = gridVisibleColumnFieldsSelector(apiRef);
let data = filteredSortedRowIds.map((id) => {
const row = {};
visibleColumnsField.forEach((field) => {
row[field] = apiRef.current.getCellParams(id, field).value;
});
return row;
});
let m = JSON.stringify(data, null, 2);
data.map((d) => {(delete d._check_,delete d.action)})
console.info(data)
Export(data,fileName)
// arrayToExcel(data)
};
return (
<GridToolbarContainer>
<Button
{...buttonBaseProps}
onClick={(e) => myfiltredRows(getFilteredRows)
}> Filtered rows</Button>
</GridToolbarContainer>
);
}
this is the function that converts my array to excel
const Export = (a, fileName) => {
const ws = XLSX.utils.json_to_sheet(a);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
I have a webapi invoked that is working properly:
const [pItem, setPItem] = useState([]);
const [weight, setWeight] = useReducer(weightHandler, 0.0);
useEffect(() => {
setLoading(true);
let mounted = true;
(async function () {
await getPlantInfoById(itemId)
.then(item => {
if (mounted) {
setPItem(item)
setLoading(false);
}
})
})();
return () => { mounted = false; }
}, [itemId])
Here pItem contains data now I have another filled called weight(which can be changed by a user) .
So I need some calculations according to the weight changes:
const PaymentCalculator = function () {
const [item] = [...pItem];
const priceWithDiscount = DiscountCalc(item.price, item.discount);
const divideWeight = weight / item.weight;
const result = (divideWeight * priceWithDiscount) * 1000;
return result;
}
const use = useMemo(() => PaymentCalculator(), [weight])
But it seems PaymentCalculator invoked before useEffect !!
How can I fix this?
If you examine the contents of paymentCalculator you'll see you've more than just weight as a dependency.
const PaymentCalculator = function () {
const [item] = [...pItem];
const priceWithDiscount = DiscountCalc(item.price, item.discount);
const divideWeight = weight / item.weight;
const result = (divideWeight * priceWithDiscount) * 1000;
return result;
}
pItem is also a dependency!
Initially pItem is an empty array, and since all hooks are called on each render cycle, this would mean that item is undefined on the initial render and accessing item.price and item.discount will throw an error for attempting to "access X of undefined".
Add pItem to the dependency array and provide a fallback value.
const paymentCalculator = function() {
const [item = {}] = [...pItem];
const priceWithDiscount = discountCalc(item.price, item.discount);
const divideWeight = weight / item.weight;
const result = (divideWeight * priceWithDiscount) * 1000;
return result;
}
...
const use = useMemo(() => PaymentCalculator(), [pItem, weight]);
I wanted to test that a count increases whenever I clicked on a button, but it seems not to work. Please Help! Here is the code...
describe('checkbtn', () => {
it('onClick', () => {
const { queryByTitle } = render(<Counter />);
const { queryByTitle } = render(<Counter />);
const btn = queryByTitle('button1');
const count = queryByTitle('count');
expect(count.innerHTML).toBe(count.innerHTML);
fireEvent.click(btn);
expect(count.innerHTML).toBe(count.innerHTML + 1);
})
})
First of all you expect some state to equal the same state + 1 here:
expect(count.innerHTML).toBe(count.innerHTML + 1);
It's the same as to write
const x = 2;
expect(x).toBe(x+2)
Second is that you try to add number to string which will result in not what you expect.
What you should do is to write explicit values in your test:
describe('checkbtn', () => {
it('onClick', () => {
const { queryByTitle } = render(<Counter />);
const btn = queryByTitle('button1');
const count = queryByTitle('count');
expect(count.innerHTML).toBe('1');
fireEvent.click(btn);
expect(count.innerHTML).toBe('2');
})
})
I am researching how I can do a multi-word search. I found this example Multi Term Filter with hooks.
const filterIt = (terms, arr) => {
if ("" === terms || terms.length < 3) return arr;
const words = terms.match(/\w+|"[^"]+"/g);
words.push(terms);
return arr.filter((a) => {
const v = Object.values(a);
const f = JSON.stringify(v).toLowerCase();
return words.every(val => f.includes(val));
});
};
const FilteredList = () => {
const [items, setItems] = useState([]);
const filterList = useCallback(({target}) => {
const searchQuery = target.value.toLowerCase();
const updatedList = filterIt(searchQuery, initialItems);
setItems(updatedList);
}, []);
I'm trying to modify it so that I can separate words with a space. For example, I enter "iron suit", and the search gave me:
At the moment, the search does not return anything:
Any advice would be greatly appreciated.
I played a bit with your sample code and came up with this:
const filterIt = (terms, arr) => {
if ("" === terms || terms.length < 3) return arr;
var words = terms.match(/"[^"]+"|\w+/g);
words = words.map(val => val.replace(/\"/g, ""));
//words.push(terms);
return arr.filter((a) => {
const v = Object.values(a);
const f = JSON.stringify(v).toLowerCase();
return words.every(val => f.includes(val));
});
};
which allows me to search without quotes
and with quotes
I'm pretty new to react so sorry if the solution is obvious.
For my project, I need to connect to a websocket inside a Component with the following code
let id = 2;
const Dashboard = () => {
const [apiOutput, setApiOutput] = useState([]);
const [apiConnectionStatus, setApiConnectionStatus] = useState(false);
const ws = new WebSocket("ws://XXXXXXX/api/websocket");
const initWebsocket = () => {
ws.addEventListener("open", () => {
ws.send('{"type":"auth", "api_password":"XXXX"}');
ws.send('{"id": 1, "type": "get_states"}');
ws.send(
'{"id": 2, "type": "subscribe_events", "event_type": "state_changed"}'
);
});
ws.onopen = () => {
setApiConnectionStatus(true);
};
ws.onmessage = evt => {
const message = JSON.parse(evt.data);
setApiOutput(message);
};
ws.onclose = error => {
console.log(error);
setApiConnectionStatus(false);
};
};
useEffect(() => {
initWebsocket();
}, []);
const switchHandler = entity_id => {
console.log("switch =" + ws.readyState);
id++;
const command = `{"id": ${id}, "type": "call_service", "domain": "switch", "service": "toggle", "service_data": { "entity_id": "${entity_id}"}}`;
ws.send(command);
};
The SwitchHandler function is sent to a child Component via props and triggers as expected.
The apiOutput State works as expected as well.
The problem is that ws.send(command) is not working (like not triggering) even though ws.readyState returns 1 inside the SwitchHandler function.
Is there anything obvious that I'm missing ?
Ok found the answer.
Just had to declare let ws; before the Dashboard function.
let ws;
let id = 2;
const Dashboard = () => {
const [apiOutput, setApiOutput] = useState([]);
const [apiConnectionStatus, setApiConnectionStatus] = useState(false);
ws = new WebSocket("ws://XXXXXXX/api/websocket");
...