How to display data read from a file using Electron and React? - node.js

My goal is simply to display data (using React) from a file stored locally with my Electron app. I've gotten halfway there in actually reading and processing the data, I just can't figure out how to display it.
Here's what I have for my file read:
export function read() {
let values = [];
fs.readFile(
path.resolve(__dirname, './files/test.txt'),
'utf-8',
(err, data) => {
if (err) throw err;
values = data.toString().split('\n');
const listItems = values.map(val => <p>{val}</p>);
return listItems;
}
);
}
This works correctly, and I've console logged all the correct values.
The part that's confusing me is when I want to display it. Here's my react component:
// #flow
import React, { Component } from 'react';
import styles from './ReadFile.css';
import { read } from '../actions/fileread';
type Props = {};
export default class ReadFile extends Component<Props> {
props: Props;
render() {
const result = read();
return (
<div className={styles.container} data-tid="container">
<p>Read from File</p>
{result}
</div>
);
}
}
What I would expect this to do is call the read function, store it in result and then print the results with {result}. What it does instead is display nothing. It also gives no errors.
I have a feeling this has to do with some odd server/client relationship between the react frontend and the node.js "backend" reading the file. I'm not sure how to create a simple interface between these two components to get them to work.

As mentioned in my comment your code is async and your read() method is not returning anything. You should have something close to this:
export default class ReadFile extends Component<Props> {
props: Props;
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
read((result) => {
this.setState({
result,
});
});
}
render() {
return (
<div className={styles.container} data-tid="container">
<p>Read from File</p>
{this.state.result}
</div>
);
}
}
And for read() this:
export function read(callback) {
let values = [];
fs.readFile(
path.resolve(__dirname, './files/test.txt'),
'utf-8',
(err, data) => {
if (err) throw err;
values = data.toString().split('\n');
const listItems = values.map(val => <p>{val}</p>);
return callback(listItems);
}
);
}

Related

RTK Query in Redux-Toolkit is returning data of undefined, when I console.log the data it appears in console

I was trying to display an array of data fetched from my custom server with RTK Query using Next.js (React framework). And this is my first time using RTK Query. Whenever I console.log the data, it appears in the browser console. But whenever I try to map the data to render it in the browser, it keeps throwing an error saying Cannot read properties of undefined (reading 'map').
I figured Next.js always throws an error if an initial state is undefined or null even if the state change. This link talked about solving the problem using useMemo hook https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics
But I didn't understand it well. Please kindly help me out with displaying the data.
Here is the BaseQuery function example I followed, it was derived from redux toolkit docmentation https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
import axios from "axios";
const axiosBaseQuery =
({ baseUrl } = { baseUrl: "" }) =>
async ({ url, method, data }) => {
try {
const result = await axios({ url: baseUrl + url, method, data });
return { data: result.data };
} catch (axiosError) {
let err = axiosError;
return {
error: { status: err.response?.status, data: err.response?.data },
};
}
};
export default axiosBaseQuery;
I make the GET request here
import { createApi } from "#reduxjs/toolkit/query/react";
import axiosBaseQuery from "./axiosBaseQuery";
export const getAllCarsApi = createApi({
reducerPath: "getAllCarsApi",
baseQuery: axiosBaseQuery({
baseUrl: "http://localhost:5000/",
}),
endpoints(build) {
return {
getAllCars: build.query({
query: () => ({ url: "all-cars", method: "get" }),
}),
};
},
});
export const { useGetAllCarsQuery } = getAllCarsApi;
This is my redux store
import { configureStore } from "#reduxjs/toolkit";
import { getAllCarsApi } from "./getAllCarsApi";
import { setupListeners } from "#reduxjs/toolkit/dist/query";
const store = configureStore({
reducer: { [getAllCarsApi.reducerPath]: getAllCarsApi.reducer },
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(getAllCarsApi.middleware),
});
setupListeners(store.dispatch);
export default store;
I provide the store to the _app.js file.
import "../styles/globals.css";
import axios from "axios";
import { MyContextProvider } from "#/store/MyContext";
import { Provider } from "react-redux";
import store from "#/store/ReduxStore/index";
axios.defaults.withCredentials = true;
function MyApp({ Component, pageProps }) {
return (
<MyContextProvider>
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</MyContextProvider>
);
}
export default MyApp;
I get the data here in my frontend.
import { useGetAllCarsQuery } from "#/store/ReduxStore/getAllCarsApi";
const theTest = () => {
const { data, isLoading, error } = useGetAllCarsQuery();
return (
<div>
{data.map((theData, i) => (
<h1 key={i}>{theData}</h1>
))}
<h1>Hello</h1>
</div>
);
};
export default theTest;
This is a timing thing.
Your component will always render immediately and it will not defer rendering until data is there. That means it will also render before your data has been fetched. So while the data is still loading, data is undefined - and you try to map over that.
You could do things like just checking if data is there to deal with that:
const theTest = () => {
const { data, isLoading, error } = useGetAllCarsQuery();
return (
<div>
{data && data.map((theData, i) => (
<h1 key={i}>{theData}</h1>
))}
<h1>Hello</h1>
</div>
);
};

Pass parameter in React Url to get relative data

I created a express api where when we pass parameter to url say localhost:8000/data?music=rock it gives me data associated with it and if i pass say localhost:8000/data?music=rap and gives me data associated with it....P.S. there are many genre of music classical and so on and data associated with it.
Express api:: connected to mongoose where I scraped a data and stored in mongodb from where it feteches the data
app.get('/data'.(res,req)=>{
count music = req.query.music
collection.find({"music":music},(err,result)=>{
if(err):
return res.status(500).send(err);
}
else{
console.log(docs);
res.send(docs);
}
});
});
React JS::::
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {apiResponse:"",genre:""};
}
async callAPI(e) {
console.log(e.target.value);
const url = `http://localhost:8000/data?music=${e.target.value}`;
const response = await fetch(url);
console.log(response);
const textResponse = response.text();
console.log(textResponse);
this.setState({apiResponse:textResponse});
}
render() {
const {apiResponse} = this.state;
console.log(apiResponse);
return (
<>
<select name="continent" id="continent" onClick={e=>this.callAPI(e)}>
<option value=" ">--Please choose an option--</option>
<option value="Europe">Europe</option>
<option value="North America">North America</option>
</select>
{apiResponse && <h1>{apiResponse.title}</h1>}
</>
);
}
}
export default App;
Now i connected my express api with react but as you can see i have provided static path as
fetch("http://localhost:8000/data?music=Rock")
to get the data associated with rock music.
But I want react to fetch different genre of music dynamically from API without using a static path to fetch data. like react port:: localhost:3000/music=rock and it gives me data of rock music or classical and it gives me data of that.
Can anyone from community guide me on what method can be used or any article? Will be really appreciated. Cheers!!
You can use the select element to trigger an onChange event to fetch data from the user. Here, I replaced the url with template literals. After the fetch is complete and apiResponse is set, you can then map the data in the return block.
Here is a working sandbox.
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: "", genre: "" };
}
async callAPI(e) {
console.log(e.target.value);
const url = `http://localhost:8000/data?music=${e.target.value}`;
const response = await fetch(url);
console.log(response);
const textResponse = response.text();
console.log(textResponse);
this.setState({ apiResponse: textResponse });
}
render() {
return (
<>
<select name="genre" id="genre" onChange={e => this.callAPI(e)}>
<option value="">--Please choose an option--</option>
<option value="Rap">Rap</option>
<option value="Rock">Rock</option>
</select>
</>
);
}
}
export default App;
You can use axis for the request and set the params, in this case, the music
axios.get('http://localhost:8000/data', {
params: {
music: 'rap'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
You can read more about axis here
You can add a controlled input field for music and use this.state.music in the fetch URL
https://reactjs.org/docs/forms.html#controlled-components

Performing a fetch request only on state update

I'm new to React and I'm trying to figure out how to work with fetch correctly.
I have a React component that I'd like to update from a remote server whenever its parent's state updated.
i.e - parent's state changed -> myComponent calls remote server and re-renders itself.
I've tried the following:
If I only perform the .fetch call on componentDidMount, it disregards any state updates.
If I perform the .fetch call on componentDidUpdate as well it calls the server endlessly (I assume because of some update-render loop)
I have tried using the componentWillReceiveProps function, and it works, but I understand it's now deprecated.
How can I achieve this kind of behavior without componentWillReceiveProps ?
class myComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
images: []
};
}
componentDidMount() {
let server = "somethingserver.html";
fetch(server)
.then(res => {
if (res.ok) {
return res.json();
}
else {
console.log(res);
throw new Error(res.statusText);
}
})
.then(
(result) => {
this.setState({
images: result.items
});
}
).catch(error => console.log(error));
}
componentWillReceiveProps(nextprops) {
if (this.state !== nextprops.state) {
//same as componentDidMount
}
}
render() {
return (
<Gallery images={this.state.images} enableImageSelection={false} />
);
}
}
Given our conversation in the comments I can only assume that your search term is in a parent component. So what I recommend you to do is pass it to this component as a prop so you can do the following in your componentDid update:
componentDidUpdate(prevProps) {
const { searchTerm: previousSearch } = prevProps;
const { searchTerm } = this.props;
if (searchTerm !== previousSearch) fetch() ....
}
You can use getDerivedStateFromProps. It's the updated version of componentWillReceiveProps.
You should also read this, though: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Using props to update internal state in a component can lead to complex bugs and there are often better solutions.

How to show the imported csv data into a table using reactjs?

I have an upload button to import only CSV files to my Reactjs application. I can successfully upload the data(CSV) using React file reader but now I want to show the CSV data it into a table. I think this could help me but I cannot understand how to use it https://github.com/marudhupandiyang/react-csv-to-table here. Below is my code:
import React, { Component } from 'react';
import ReactFileReader from 'react-file-reader';
import { CsvToHtmlTable } from 'react-csv-to-table';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
csvData: ''
};
}
handleFiles = files => {
var reader = new FileReader();
reader.onload = function(e) {
// Use reader.result
this.setState({
csvData: reader.result
})
}
reader.readAsText(files[0]);
}
render() {
return (
<div>
<ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
<button className='btn'>Upload</button>
</ReactFileReader>
<CsvToHtmlTable
data={this.state.csvData}
csvDelimiter=","
tableClassName="table table-striped table-hover"
/>
</div>
);
}
}
export default App;
please help. It's very important to me.
You almost got it. Be careful when using setState inside a function. This reference will be re-binded to the function scope. Use this instead
handleFiles = files => {
let reader = new FileReader();
reader.onload = () => {
// Use reader.result
this.setState({
csvData: reader.result
})
}
reader.readAsText(files[0]);
}
You can test it here.
https://codesandbox.io/s/qlj338vnkj
You can use this to show up csv in react table. You can use papaparse
import Papa from 'papaparse';
And then fetch the csv
fetchCsv() {
return fetch('/data/data.csv').then(function (response) {
let reader = response.body.getReader();
let decoder = new TextDecoder('utf-8');
return reader.read().then(function (result) {
return decoder.decode(result.value);
});
});
}
async getCsvData() {
let csvData = await this.fetchCsv();
let results = Papa.parse(csvData, { header: true })
this.getData(results)
}
https://github.com/manaspandey45/react-csv-data-table

How to render the React component with dynamic data realtime from socket.io high efficiency

My front-end page is made by React + Flux, which sends the script data to back-end nodejs server.
The script data is an Array which contains the linux shell arguments (more than 100000). When to back-end received, it will execute the linux shell command.
Just an example:
cat ~/testfile1
cat ~/testfile2
.
.
.
(100000 times ...etc)
When the backend finished one of the linux shell commands, I can save the readed content to result data. Therefore, socket.io will emit the result data to the front-end.
I want to get the result data from my webpage in real time, so I have done some stuff in my project below.
My React component code:
import React from 'react';
import AppActions from '../../../actions/app-actions';
import SocketStore from '../../../stores/socket-store';
import ResultStore from '../../../stores/result-store';
function getSocket () {
return SocketStore.getSocket();
}
function getResult () {
return ResultStore.getResultItem();
}
class ListResultItem extends React.Component {
constructor () {
super();
}
render () {
return <li>
{this.props.result.get('name')} {this.props.result.get('txt')}
</li>;
}
}
class ShowResult extends React.Component {
constructor () {
super();
this.state = {
socket: getSocket(),
result: getResult()
};
}
componentWillMount () {
ResultStore.addChangeListener(this._onChange.bind(this));
}
_onChange () {
this.setState({
result: getResult()
});
}
render () {
return <div>
<ol>
{this.state.result.map(function(item, index) {
return <ListResultItem key={index} result={item} />;
})}
</ol>
</div>;
}
componentDidMount () {
this.state.socket.on('result', function (data) {
AppActions.addResult(data);
});
}
}
My Flux store (ResultStore) code:
import AppConstants from '../constants/app-constants.js';
import { dispatch, register } from '../dispatchers/app-dispatcher.js';
import { EventEmitter } from 'events';
import Immutable from 'immutable';
const CHANGE_EVENT = 'changeResult';
let _resultItem = Immutable.List();
const _addResult = (result) => {
let immObj = Immutable.fromJS(result);
_resultItem = _resultItem.push(immObj);
}
const _clearResult = () => {
_resultItem = _resultItem.clear();
}
const ResultStore = Object.assign(EventEmitter.prototype, {
emitChange (){
this.emit( CHANGE_EVENT );
},
addChangeListener (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getResultItem () {
return _resultItem;
},
dispatcherIndex: register(function (action) {
switch (action.actionType) {
case AppConstants.ADD_RESULT:
_addResult(action.result);
break;
case AppConstants.CLEAR_RESULT:
_clearResult();
break;
}
ResultStore.emitChange();
})
});
However, the page will become very slow after rendering more than 1000 datas. How to enhance the performance for rendering? I need to execute the linux script persistently more than 3 days. Any solutions? Thanks~
Is there any need to render all the data on screen? If not then there are a few ways to deal with cutting down the amount of visible data.
Filter / Search
You can provide a search/filter component that complements the list and creates a predicate function that can be used to determine whether each item should or should not be rendered.
<PredicateList>
<Search />
<Filter />
{this.state.result
.filter(predicate)
.map(function(item, index) {
return <ListResultItem key={index} result={item} />;
})
}
</PredicateList>
Lazy Load
Load the items only when they are asked for. You can work out whether item is needed by keeping track of whether it would be onscreen, or whether the mouse was over it.
var Lazy = React.createClass({
getInitialState: function() {
return { loaded: false };
},
load: function() {
this.setState({ loaded: true });
},
render: function() {
var loaded = this.state.loaded,
component = this.props.children,
lazyContainer = <div onMouseEnter={this.load} />;
return loaded ?
component
lazyContainer;
}
});
Then simply wrap your data items inside these Lazy wrappers to have them render when they are requested.
<Lazy>
<ListResultItem key={index} result={item} />
</Lazy>
This ensures that only data needed by the user is seen. You could also improve the load trigger to work for more complex scenarios, such as when the component has been onscreen for more then 2 seconds.
Pagination
Finally, the last and most tried and tested approach is pagination. Choose a limit for a number of data items that can be shown in one go, then allow users to navigate through the data set in chunks.
var Paginate = React.createClass({
getDefaultProps: function() {
return { items: [], perPage: 100 };
},
getInitialState: function() {
return { page: 0 };
},
next: function() {
this.setState({ page: this.state.page + 1});
},
prev: function() {
this.setState({ page: this.state.page - 1});
},
render: function() {
var perPage = this.props.perPage,
currentPage = this.state.page,
itemCount = this.props.items.length;
var start = currentPage * perPage,
end = Math.min(itemCount, start + perPage);
var selectedItems = this.props.items.slice(start, end);
return (
<div className='pagination'>
{selectedItems.map(function(item, index) {
<ListResultItem key={index} result={item} />
})}
<a onClick={this.prev}>Previous {{this.state.perPage}} items</a>
<a onClick={this.next}>Next {{this.state.perPage}} items</a>
</div>
);
}
});
These are just very rough examples of implementations for managing the rendering of large amounts of data in efficient ways, but hopefully they will make enough sense for you to implement your own solution.

Resources