How to process large files efficiently in react.js - javascript

I am trying to render the hex values in a file uploaded using react.
When I upload big files, say 10MB, the page crashes, but sites like http://mikach.github.io/hex-editor/ works like a charm. I don't understand what am I doing wrong.
Below is the code which does the same
import React from "react";
class App extends React.PureComponent {
constructor(props) {
super(props);
this.fileReader = null;
this.state = {
filecontent: [],
decodingSection: [
{ type: "BigUint64", startIndex: "0", endIndex: "0" },
{ type: "BigUint64", startIndex: "0", endIndex: "0" }
]
};
}
handleFileRead = () => {
const typedArray = new Uint8Array(this.fileReader.result);
const untypedArrray = [];
const iii = typedArray.values();
while (true) {
const { value, done } = iii.next();
if (done) {
break;
}
const hexValue = value.toString(16);
untypedArrray.push(hexValue.length === 1 ? `0${hexValue}` : hexValue);
}
this.setState({
filecontent: untypedArrray
});
};
handleFileChosen = file => {
this.fileReader = new FileReader();
this.fileReader.onloadend = this.handleFileRead;
this.fileReader.readAsArrayBuffer(file);
};
render() {
return (
<div>
<input
type={"file"}
id={"file"}
onChange={e => this.handleFileChosen(e.target.files[0])}
/>
<br />
{this.state.filecontent.length > 0 && (
<div>No Bytes present {this.state.filecontent.length}</div>
)}
{this.state.filecontent.map(each => `${each} `)}
</div>
);
}
}
export default App;

One possible cause could be the map this.state.filecontent.map(each => '${each} ') in the render method, thought I'm not sure.
I slightly modified the code, so that it saves the whole character sequence into a string called contents (using the array's join method) and then renders it at once.
You can take a look and give it a try here. At least, it worked for me on a 10Mb file :)

Related

Re-rendering throws off my logic when using react-dnd

Right now I'm building a DnD game.
It looks like this:
When I drop an answer over a slot, the answer should be in that exact place, so the order matters.
My approach kind of works, but not perfectly.
So, in the parent component I have two arrays which store the slots' content and the answers' content.
The problem is easy to understand, you don't have to look at the code in-depth, just mostly follow my text :)
import DraggableGameAnswers from './DraggableGameAnswers';
import DraggableGameSlots from './DraggableGameSlots';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useState } from 'react';
type DraggableGameStartProps = {
gameImages: Array<string>,
gameAnswers: Array<string>,
numberOfGameAnswers?: number,
typeOfAnswers: string,
correctAnswer: string
}
function DraggableGameStart(props: DraggableGameStartProps) {
const [slots, setSlots] = useState<string[]>(["", "", "", ""]);
const [answers, setAnswers] = useState<string[]>(props.gameAnswers);
return (
<DndProvider backend={HTML5Backend}>
<div className="draggable-game-content">
<div className="draggable-game">
<DraggableGameSlots
answers={answers}
slots={slots}
setAnswers={setAnswers}
setSlots={setSlots}
numberOfAnswers={4}
slotFor={props.typeOfAnswers}
/>
<DraggableGameAnswers
gameAnswers={answers}
numberOfGameAnswers={props.numberOfGameAnswers}
typeOfAnswers={props.typeOfAnswers}
/>
</div>
</div>
</DndProvider>
);
}
export default DraggableGameStart;
DraggableGameSlots is then a container, which loops through props.slots and renders each slot.
import React, { useState } from "react";
import DraggableGameSlot from "./DraggableGameSlot";
type DraggableGameSlotsProps = {
answers: string[],
slots: string[],
setAnswers: any,
setSlots: any,
numberOfAnswers: number,
slotFor: string
}
function DraggableGameSlots(props: DraggableGameSlotsProps) {
return (
<div className="draggable-game-slots">
{
props.slots.map((val, index) => (
<DraggableGameSlot
index={index}
typeOf={props.slotFor === "text" ? "text" : "image"}
key={index}
answers={props.answers}
slots={props.slots}
setAnswers={props.setAnswers}
setSlots={props.setSlots}
toDisplay={val === "" ? "Drop here" : val}
/>
))
}
</div>
);
}
export default DraggableGameSlots;
In DraggableGameSlot I make my slots a drop target. When I drop an element, I iterate through the slots, and when I reach that element's position in the array, I modify it with the answer.
Until now everything works fine, as expected, I just wrote this for context.
E.g. if the drop target's index is 2, I modify the 3rd position in the slots array. (slots2 for 0-index based)
import { useEffect } from 'react';
import { useDrop } from 'react-dnd';
import './css/DraggableGameSlot.css';
import DraggableGameImage from './DraggableGameImage';
type DraggableGameSlotProps = {
index: number,
typeOf: string,
answers: string[],
slots: string[],
setAnswers: any,
setSlots: any,
toDisplay: string
}
function DraggableGameSlot(props: DraggableGameSlotProps) {
const [{ isOver }, drop] = useDrop(() => ({
accept: "image",
drop(item: { id: string, toDisplay: string }) {
props.setAnswers(props.answers.filter((val, index) => index !== parseInt(item.id)));
props.setSlots(props.slots.map((val, index) => {
if (props.index === index) {
console.log("ITEM " + item.toDisplay);
return item.toDisplay;
}
return val;
}));
},
collect: (monitor) => ({
isOver: !!monitor.isOver(),
})
}), [props.slots])
// useEffect(() => console.log("answers " +props.answers), [props.answers]);
// useEffect(() => console.log("slots " + props.slots), [props.slots]);
const dragClass: string = isOver ? "is-dragged-on" : "";
return (
<>
{(props.typeOf === "image" && props.toDisplay !== "Drop here") ?
<>
<span>da</span>
<DraggableGameImage
className={`game-answers-image ${dragClass}`}
imgSrc={props.toDisplay}
imgAlt={"test"}
dndRef={drop}
/>
</>
:
<div className={`draggable-game-slot draggable-game-slot-for-${props.typeOf} ${dragClass}`} ref={drop}>
<span>{props.toDisplay}</span>
</div>
}
</>
)
}
export default DraggableGameSlot;
The problem comes with the logic in DraggableGameAnswer.
First, the container, DraggableGameAnswer. Using the loop, I pass that "type" (it is important because from there the error happens)
DraggableGameAnswers.tsx
import './css/DraggableGameAnswers.css';
import GameNext from '../GameComponents/GameNext';
import DraggableGameAnswer from './DraggableGameAnswer';
import { useEffect } from 'react';
type DraggableGameAnswersProps = {
gameAnswers: Array<string>,
numberOfGameAnswers?: number,
typeOfAnswers: string
}
function DraggableGameAnswers(props: DraggableGameAnswersProps) {
let toDisplay: Array<string>;
if(props.numberOfGameAnswers !== undefined)
{
toDisplay = props.gameAnswers.slice(props.numberOfGameAnswers);
}
else
{
toDisplay = props.gameAnswers;
}
useEffect(() => console.log(toDisplay));
return (
<div className="draggable-game-answers">
{
toDisplay.map((val, index) => (
<DraggableGameAnswer
key={index}
answer={val}
typeOfAnswer={props.typeOfAnswers}
type={`answer${index}`}
/>
))}
<GameNext className="draggable-game-verify" buttonText="Verify"/>
</div>
);
}
export default DraggableGameAnswers;
In DraggableGameAnswer, I render the draggable answer:
import DraggableGameImage from "./DraggableGameImage";
import "./css/DraggableGameAnswer.css";
import { useDrag } from "react-dnd";
import { ItemTypes } from "./Constants";
type DraggableGameAnswerProps = {
answer: string,
typeOfAnswer: string,
type: string
}
function DraggableGameAnswer(props: DraggableGameAnswerProps) {
const [{ isDragging }, drag] = useDrag(() => ({
type: "image",
item: { id: ItemTypes[props.type],
toDisplay: props.answer,
typeOfAnswer: props.typeOfAnswer },
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
})
}))
return (
<>
{props.typeOfAnswer === "image" ?
<DraggableGameImage
className="draggable-game-image-answer"
imgSrc={props.answer}
imgAlt="test"
dndRef={drag}
/> :
<div className="draggable-game-text-answer" ref={drag}>
{props.answer}
</div>
}
</>
);
}
export default DraggableGameAnswer;
Constants.tsx (for ItemTypes)
export const ItemTypes: Record<string, any> = {
answer0: '0',
answer1: '1',
answer2: '2',
answer3: '3'
}
Okay, now let me explain what's happening.
The error starts because of the logic in DraggableGameAnswers container - I set the type using the index for the loop.
Everything works fine at the beginning. Then, let's say, I move answer3 in in the 4th box. It looks like this now:
It is working fine until now.
But now, the components have re-rendered, the map runs again, but the array is shorter with 1 and answer1's type will be answer1, answer2's type will be answer2, and answer4's type will be answer3.
So, when I drag answer4 over any box, I will get another answer3, like this:
How can I avoid this behavior and still get answer4 in this situation? I'm looking for a react-style way, better than my idea that I'll describe below.
So, here is how I delete an answer from the answers array:
props.setAnswers(props.answers.filter((val, index) => index !== parseInt(item.id)));
I can just set the deleted's answer position to NULL, to keep my array length for that index, and when I render the answers if the value is NULL, just skip it.

Typsetting Problem in better-react-mathjax

I am using better-react-mathjax for equation writing and reading. Basically, I used the MathJax in my equation with a question. When it first loads it does not create a problem.
But when I use to filter using React sate it creates the Typesetting problem and the next app is crashed.
How can I fix the problem?
MathJax
import React from 'react'
import { MathJax, MathJaxContext } from "better-react-mathjax";
const config = {
loader: { load: ["input/asciimath"] }
};
export const MathJaxOutput = ({ text }) => {
return <MathJaxContext config={config} version={3}>
<MathJax dynamic inline>
{text}
</MathJax>
</MathJaxContext>
}
And the error screenshot is
When mark and course name changed automatically loads the related questions.
state = {
courseName: '',
selectedTopics: [],
mark: null,
questions:[]
}
componentDidUpdate(prevProps, prevState) {
if (this.state.courseName !== prevState.courseName || this.state.selectedTopics !== prevState.selectedTopics || this.state.mark !== prevState.mark) {
if (this.state.courseName) {
this.props.getCourseQuestions(this.state.courseName, this.state.selectedTopics, this.state.mark);
}
}
}
Output render
{
this.state.questions.map((question, questionIndex) => (
<div className='input-question-field-items' key={questionIndex}>
<div className='preview-field-item'>
<MathJaxOutput text={<p>{question.questionInput.question}</p>} />
</div>
</div>
}

React - How can I parse large JSON objects for graphing. Struggling to do so with State

I'm having trouble parsing large JSON objects from my Axios calls and setting them as a state to then be passed as X and Y axis data for graphing in react-chartist. For my case, I'm charting stock market data.
I have been trying to parse the data using state hooks, chartData, but can't get it working, like so response.data.symbol, response.data.adj_close, and response.data.date
I also tried creating three different states, for X, Y, and symbol data taken directly from the axios call, but wasn't able to accomplish so.
Here is the code I'm using:
export default function Graph() {
const [chartData, setChartData] = useState([])
const getData = () => {
axiosInstance
.get('price/' + slug)
.then(result => setChartData(result.data))
}
useEffect(() => {
getData()
}, [])
const graphChart = () =>
{
var data = {
labels: //date values from JSON object
series: //adj_close values from JSON object
};
var options = {
width: 500,
height: 400
};
return (
<ChartistGraph data={data} options={options} type="Line" />
);
};
return (
<Container>
<Grid>
{graphChart()}
</Grid>
</Container>
);
};
Am I approaching this wrong? Is there a simpler way to do so?
I've added the data to replicate the problem, which basically is, how can I parse large objects like this? Keeping in mind that each row needs to be grouped by it's respective symbol for graphing. In the data below, there are 8 companies worth of data. Putting all of this data on a graph would be bad, but if I knew how to parse specific symbols, then I will be able to accomplish graphing on my own.
[{"symbol":"PG","date":"2020-12-04","adj_close":137.47},
{"symbol":"HSY","date":"2020-12-04","adj_close":150.87},
{"symbol":"CLX","date":"2020-12-04","adj_close":199.98},
{"symbol":"COST","date":"2020-12-04","adj_close":373.43},
{"symbol":"MDLZ","date":"2020-12-04","adj_close":59.03},
{"symbol":"K","date":"2020-12-04","adj_close":62.37},
{"symbol":"KHC","date":"2020-12-04","adj_close":34.12},
{"symbol":"PEP","date":"2020-12-04","adj_close":145.85},
{"symbol":"PG","date":"2020-12-07","adj_close":137.68},
{"symbol":"HSY","date":"2020-12-07","adj_close":149.72},
{"symbol":"CLX","date":"2020-12-07","adj_close":200.61},
{"symbol":"COST","date":"2020-12-07","adj_close":373.33},
{"symbol":"MDLZ","date":"2020-12-07","adj_close":58.41},
{"symbol":"K","date":"2020-12-07","adj_close":61.95},
{"symbol":"KHC","date":"2020-12-07","adj_close":33.6},
{"symbol":"PEP","date":"2020-12-07","adj_close":145.37},
{"symbol":"PG","date":"2020-12-08","adj_close":138.05},
{"symbol":"HSY","date":"2020-12-08","adj_close":150.63},
{"symbol":"CLX","date":"2020-12-08","adj_close":202.88},
{"symbol":"COST","date":"2020-12-08","adj_close":377.6},
{"symbol":"MDLZ","date":"2020-12-08","adj_close":58.29},
{"symbol":"K","date":"2020-12-08","adj_close":62.55},
{"symbol":"KHC","date":"2020-12-08","adj_close":34.34},
{"symbol":"PEP","date":"2020-12-08","adj_close":145.52},
{"symbol":"PG","date":"2020-12-09","adj_close":136.41},
{"symbol":"HSY","date":"2020-12-09","adj_close":152.14},
{"symbol":"CLX","date":"2020-12-09","adj_close":200.51},
{"symbol":"COST","date":"2020-12-09","adj_close":374.29},
{"symbol":"MDLZ","date":"2020-12-09","adj_close":57.72},
{"symbol":"K","date":"2020-12-09","adj_close":62},
{"symbol":"KHC","date":"2020-12-09","adj_close":34.22},
{"symbol":"PEP","date":"2020-12-09","adj_close":145.69},
{"symbol":"PG","date":"2020-12-10","adj_close":135.51},
{"symbol":"HSY","date":"2020-12-10","adj_close":149.7},
{"symbol":"CLX","date":"2020-12-10","adj_close":200.6},
{"symbol":"COST","date":"2020-12-10","adj_close":372.79},
{"symbol":"MDLZ","date":"2020-12-10","adj_close":57.18},
{"symbol":"K","date":"2020-12-10","adj_close":61.98},
{"symbol":"KHC","date":"2020-12-10","adj_close":34.1},
{"symbol":"PEP","date":"2020-12-10","adj_close":144.67},
{"symbol":"PG","date":"2020-12-11","adj_close":136.51},
{"symbol":"HSY","date":"2020-12-11","adj_close":149.11},
{"symbol":"CLX","date":"2020-12-11","adj_close":201.73},
{"symbol":"COST","date":"2020-12-11","adj_close":375.1},
{"symbol":"MDLZ","date":"2020-12-11","adj_close":57.4},
{"symbol":"K","date":"2020-12-11","adj_close":62.11},
{"symbol":"KHC","date":"2020-12-11","adj_close":34.07},
{"symbol":"PEP","date":"2020-12-11","adj_close":144.97},
{"symbol":"PG","date":"2020-12-14","adj_close":135.85},
{"symbol":"HSY","date":"2020-12-14","adj_close":149.14},
{"symbol":"CLX","date":"2020-12-14","adj_close":202.38},
{"symbol":"COST","date":"2020-12-14","adj_close":374.38},
{"symbol":"MDLZ","date":"2020-12-14","adj_close":57.29},
{"symbol":"K","date":"2020-12-14","adj_close":61.92},
{"symbol":"KHC","date":"2020-12-14","adj_close":34.42},
{"symbol":"PEP","date":"2020-12-14","adj_close":144.23},
{"symbol":"PG","date":"2020-12-15","adj_close":136.65},
{"symbol":"HSY","date":"2020-12-15","adj_close":150.23},
{"symbol":"CLX","date":"2020-12-15","adj_close":203.04},
{"symbol":"COST","date":"2020-12-15","adj_close":371.88},
{"symbol":"MDLZ","date":"2020-12-15","adj_close":57.45},
{"symbol":"K","date":"2020-12-15","adj_close":61.24},
{"symbol":"KHC","date":"2020-12-15","adj_close":34.33},
{"symbol":"PEP","date":"2020-12-15","adj_close":144.77},
{"symbol":"PG","date":"2020-12-16","adj_close":137.27},
{"symbol":"HSY","date":"2020-12-16","adj_close":150.28},
{"symbol":"CLX","date":"2020-12-16","adj_close":203.44},
{"symbol":"COST","date":"2020-12-16","adj_close":369.44},
{"symbol":"MDLZ","date":"2020-12-16","adj_close":57.2},
{"symbol":"K","date":"2020-12-16","adj_close":61.5},
{"symbol":"KHC","date":"2020-12-16","adj_close":34.43},
{"symbol":"PEP","date":"2020-12-16","adj_close":144.89},
{"symbol":"PG","date":"2020-12-17","adj_close":138.25},
{"symbol":"HSY","date":"2020-12-17","adj_close":151.61},
{"symbol":"CLX","date":"2020-12-17","adj_close":202.34},
{"symbol":"COST","date":"2020-12-17","adj_close":370.29},
{"symbol":"MDLZ","date":"2020-12-17","adj_close":57.93},
{"symbol":"K","date":"2020-12-17","adj_close":62.48},
{"symbol":"KHC","date":"2020-12-17","adj_close":34.62},
{"symbol":"PEP","date":"2020-12-17","adj_close":145.71},
{"symbol":"PG","date":"2020-12-18","adj_close":139.04},
{"symbol":"HSY","date":"2020-12-18","adj_close":150.88},
{"symbol":"CLX","date":"2020-12-18","adj_close":203.17},
{"symbol":"COST","date":"2020-12-18","adj_close":367},
{"symbol":"MDLZ","date":"2020-12-18","adj_close":58.32},
{"symbol":"K","date":"2020-12-18","adj_close":62.08},
{"symbol":"KHC","date":"2020-12-18","adj_close":34.77},
{"symbol":"PEP","date":"2020-12-18","adj_close":146.93},
{"symbol":"PG","date":"2020-12-21","adj_close":137.52},
{"symbol":"HSY","date":"2020-12-21","adj_close":149.66},
{"symbol":"CLX","date":"2020-12-21","adj_close":202.45},
{"symbol":"COST","date":"2020-12-21","adj_close":364.97},
{"symbol":"MDLZ","date":"2020-12-21","adj_close":57.68},
{"symbol":"K","date":"2020-12-21","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-21","adj_close":34.57},
{"symbol":"PEP","date":"2020-12-21","adj_close":145.4},
{"symbol":"PG","date":"2020-12-22","adj_close":136.55},
{"symbol":"HSY","date":"2020-12-22","adj_close":148.62},
{"symbol":"CLX","date":"2020-12-22","adj_close":201.39},
{"symbol":"COST","date":"2020-12-22","adj_close":362.03},
{"symbol":"MDLZ","date":"2020-12-22","adj_close":57.16},
{"symbol":"K","date":"2020-12-22","adj_close":61.19},
{"symbol":"KHC","date":"2020-12-22","adj_close":34.39},
{"symbol":"PEP","date":"2020-12-22","adj_close":144.02},
{"symbol":"PG","date":"2020-12-23","adj_close":136.34},
{"symbol":"HSY","date":"2020-12-23","adj_close":149.45},
{"symbol":"CLX","date":"2020-12-23","adj_close":202.33},
{"symbol":"COST","date":"2020-12-23","adj_close":361.89},
{"symbol":"MDLZ","date":"2020-12-23","adj_close":57.35},
{"symbol":"K","date":"2020-12-23","adj_close":61.61},
{"symbol":"KHC","date":"2020-12-23","adj_close":34.8},
{"symbol":"PEP","date":"2020-12-23","adj_close":144.41},
{"symbol":"PG","date":"2020-12-24","adj_close":137.72},
{"symbol":"HSY","date":"2020-12-24","adj_close":149.95},
{"symbol":"CLX","date":"2020-12-24","adj_close":203.8},
{"symbol":"COST","date":"2020-12-24","adj_close":364.58},
{"symbol":"MDLZ","date":"2020-12-24","adj_close":57.85},
{"symbol":"K","date":"2020-12-24","adj_close":61.78},
{"symbol":"KHC","date":"2020-12-24","adj_close":34.98},
{"symbol":"PEP","date":"2020-12-24","adj_close":145.06},
{"symbol":"PG","date":"2020-12-28","adj_close":138.68},
{"symbol":"HSY","date":"2020-12-28","adj_close":151.8},
{"symbol":"CLX","date":"2020-12-28","adj_close":202.25},
{"symbol":"COST","date":"2020-12-28","adj_close":371.06},
{"symbol":"MDLZ","date":"2020-12-28","adj_close":58.27},
{"symbol":"K","date":"2020-12-28","adj_close":62.34},
{"symbol":"KHC","date":"2020-12-28","adj_close":35.21},
{"symbol":"PEP","date":"2020-12-28","adj_close":146.91},
{"symbol":"PG","date":"2020-12-29","adj_close":138.42},
{"symbol":"HSY","date":"2020-12-29","adj_close":151.44},
{"symbol":"CLX","date":"2020-12-29","adj_close":201.76},
{"symbol":"COST","date":"2020-12-29","adj_close":372.72},
{"symbol":"MDLZ","date":"2020-12-29","adj_close":58.45},
{"symbol":"K","date":"2020-12-29","adj_close":62.29},
{"symbol":"KHC","date":"2020-12-29","adj_close":34.9},
{"symbol":"PEP","date":"2020-12-29","adj_close":147.42},
{"symbol":"PG","date":"2020-12-30","adj_close":137.77},
{"symbol":"HSY","date":"2020-12-30","adj_close":150.53},
{"symbol":"CLX","date":"2020-12-30","adj_close":201.04},
{"symbol":"COST","date":"2020-12-30","adj_close":374.45},
{"symbol":"MDLZ","date":"2020-12-30","adj_close":58},
{"symbol":"K","date":"2020-12-30","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-30","adj_close":34.67},
{"symbol":"PEP","date":"2020-12-30","adj_close":147.31},
{"symbol":"PG","date":"2020-12-31","adj_close":139.14},
{"symbol":"HSY","date":"2020-12-31","adj_close":152.33},
{"symbol":"CLX","date":"2020-12-31","adj_close":201.92},
{"symbol":"COST","date":"2020-12-31","adj_close":376.78},
{"symbol":"MDLZ","date":"2020-12-31","adj_close":58.47},
{"symbol":"K","date":"2020-12-31","adj_close":62.23},
{"symbol":"KHC","date":"2020-12-31","adj_close":34.66},
{"symbol":"PEP","date":"2020-12-31","adj_close":148.3},
{"symbol":"PG","date":"2021-01-04","adj_close":137.82},
{"symbol":"HSY","date":"2021-01-04","adj_close":150.9},
{"symbol":"CLX","date":"2021-01-04","adj_close":200.44},
{"symbol":"COST","date":"2021-01-04","adj_close":380.15},
{"symbol":"MDLZ","date":"2021-01-04","adj_close":57.92},
{"symbol":"K","date":"2021-01-04","adj_close":61.45},
{"symbol":"KHC","date":"2021-01-04","adj_close":34.23},
{"symbol":"PEP","date":"2021-01-04","adj_close":144.27},
{"symbol":"PG","date":"2021-01-05","adj_close":138.7},
{"symbol":"HSY","date":"2021-01-05","adj_close":150.73},
{"symbol":"CLX","date":"2021-01-05","adj_close":200.01},
{"symbol":"COST","date":"2021-01-05","adj_close":375.74},
{"symbol":"MDLZ","date":"2021-01-05","adj_close":57.98},
{"symbol":"K","date":"2021-01-05","adj_close":61.8},
{"symbol":"KHC","date":"2021-01-05","adj_close":33.57},
{"symbol":"PEP","date":"2021-01-05","adj_close":144.7},
{"symbol":"PG","date":"2021-01-06","adj_close":140.16},
{"symbol":"HSY","date":"2021-01-06","adj_close":151.26},
{"symbol":"CLX","date":"2021-01-06","adj_close":197.41},
{"symbol":"COST","date":"2021-01-06","adj_close":370.02},
{"symbol":"MDLZ","date":"2021-01-06","adj_close":57.87},
{"symbol":"K","date":"2021-01-06","adj_close":61.32},
{"symbol":"KHC","date":"2021-01-06","adj_close":33.94},
{"symbol":"PEP","date":"2021-01-06","adj_close":142.93},
{"symbol":"PG","date":"2021-01-07","adj_close":138.85},
{"symbol":"HSY","date":"2021-01-07","adj_close":151.17},
{"symbol":"CLX","date":"2021-01-07","adj_close":196.43},
{"symbol":"COST","date":"2021-01-07","adj_close":367.92},
{"symbol":"MDLZ","date":"2021-01-07","adj_close":57.76},
{"symbol":"K","date":"2021-01-07","adj_close":60.89},
{"symbol":"KHC","date":"2021-01-07","adj_close":33.695},
{"symbol":"PEP","date":"2021-01-07","adj_close":142.47},
{"symbol":"PG","date":"2021-01-08","adj_close":138.79},
{"symbol":"HSY","date":"2021-01-08","adj_close":152.03},
{"symbol":"CLX","date":"2021-01-08","adj_close":197.84},
{"symbol":"COST","date":"2021-01-08","adj_close":369.94},
{"symbol":"MDLZ","date":"2021-01-08","adj_close":58.19},
{"symbol":"K","date":"2021-01-08","adj_close":60.2},
{"symbol":"KHC","date":"2021-01-08","adj_close":33.62},
{"symbol":"PEP","date":"2021-01-08","adj_close":144.18},
{"symbol":"PG","date":"2021-01-11","adj_close":137.85},
{"symbol":"HSY","date":"2021-01-11","adj_close":150.11},
{"symbol":"CLX","date":"2021-01-11","adj_close":193.73},
{"symbol":"COST","date":"2021-01-11","adj_close":364.01},
{"symbol":"MDLZ","date":"2021-01-11","adj_close":57.09},
{"symbol":"K","date":"2021-01-11","adj_close":59.37},
{"symbol":"KHC","date":"2021-01-11","adj_close":32.85},
{"symbol":"PEP","date":"2021-01-11","adj_close":142.09},
{"symbol":"PG","date":"2021-01-12","adj_close":137.05},
{"symbol":"HSY","date":"2021-01-12","adj_close":149.38},
{"symbol":"CLX","date":"2021-01-12","adj_close":194.24},
{"symbol":"COST","date":"2021-01-12","adj_close":364.2},
{"symbol":"MDLZ","date":"2021-01-12","adj_close":57.32},
{"symbol":"K","date":"2021-01-12","adj_close":58.56},
{"symbol":"KHC","date":"2021-01-12","adj_close":32.18},
{"symbol":"PEP","date":"2021-01-12","adj_close":141.43},
{"symbol":"PG","date":"2021-01-13","adj_close":137.26},
{"symbol":"HSY","date":"2021-01-13","adj_close":149.92},
{"symbol":"CLX","date":"2021-01-13","adj_close":193.74},
{"symbol":"COST","date":"2021-01-13","adj_close":366.95},
{"symbol":"MDLZ","date":"2021-01-13","adj_close":57.37},
{"symbol":"K","date":"2021-01-13","adj_close":59.14},
{"symbol":"KHC","date":"2021-01-13","adj_close":32.01},
{"symbol":"PEP","date":"2021-01-13","adj_close":142.59},
{"symbol":"PG","date":"2021-01-14","adj_close":135.8},
{"symbol":"HSY","date":"2021-01-14","adj_close":147.42},
{"symbol":"CLX","date":"2021-01-14","adj_close":195.55},
{"symbol":"COST","date":"2021-01-14","adj_close":362.35},
{"symbol":"MDLZ","date":"2021-01-14","adj_close":57.31},
{"symbol":"K","date":"2021-01-14","adj_close":59.05},
{"symbol":"KHC","date":"2021-01-14","adj_close":32.08},
{"symbol":"PEP","date":"2021-01-14","adj_close":141.76},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-19","adj_close":133.6},
{"symbol":"HSY","date":"2021-01-19","adj_close":148.75},
{"symbol":"CLX","date":"2021-01-19","adj_close":196.51},
{"symbol":"COST","date":"2021-01-19","adj_close":354.47},
{"symbol":"MDLZ","date":"2021-01-19","adj_close":57.14},
{"symbol":"K","date":"2021-01-19","adj_close":58.46},
{"symbol":"KHC","date":"2021-01-19","adj_close":32.36},
{"symbol":"PEP","date":"2021-01-19","adj_close":142.06},
{"symbol":"PG","date":"2021-01-20","adj_close":131.93},
{"symbol":"HSY","date":"2021-01-20","adj_close":149.63},
{"symbol":"CLX","date":"2021-01-20","adj_close":196.93},
{"symbol":"COST","date":"2021-01-20","adj_close":361.3},
{"symbol":"MDLZ","date":"2021-01-20","adj_close":57.1},
{"symbol":"K","date":"2021-01-20","adj_close":57.64},
{"symbol":"KHC","date":"2021-01-20","adj_close":32.86},
{"symbol":"PEP","date":"2021-01-20","adj_close":141.33},
{"symbol":"PG","date":"2021-01-21","adj_close":131.01},
{"symbol":"HSY","date":"2021-01-21","adj_close":148.98},
{"symbol":"CLX","date":"2021-01-21","adj_close":197.21},
{"symbol":"COST","date":"2021-01-21","adj_close":362.8},
{"symbol":"MDLZ","date":"2021-01-21","adj_close":56.12},
{"symbol":"K","date":"2021-01-21","adj_close":57.89},
{"symbol":"KHC","date":"2021-01-21","adj_close":32.78},
{"symbol":"PEP","date":"2021-01-21","adj_close":139.61},
{"symbol":"PG","date":"2021-01-22","adj_close":130},
{"symbol":"HSY","date":"2021-01-22","adj_close":148.2},
{"symbol":"CLX","date":"2021-01-22","adj_close":202.35},
{"symbol":"COST","date":"2021-01-22","adj_close":362.3},
{"symbol":"MDLZ","date":"2021-01-22","adj_close":56.25},
{"symbol":"K","date":"2021-01-22","adj_close":58.3},
{"symbol":"KHC","date":"2021-01-22","adj_close":32.91},
{"symbol":"PEP","date":"2021-01-22","adj_close":138.59},
{"symbol":"PG","date":"2021-01-25","adj_close":132.24},
{"symbol":"HSY","date":"2021-01-25","adj_close":147.53},
{"symbol":"CLX","date":"2021-01-25","adj_close":211.96},
{"symbol":"COST","date":"2021-01-25","adj_close":361.88},
{"symbol":"MDLZ","date":"2021-01-25","adj_close":56.87},
{"symbol":"K","date":"2021-01-25","adj_close":59.84},
{"symbol":"KHC","date":"2021-01-25","adj_close":33.75},
{"symbol":"PEP","date":"2021-01-25","adj_close":140.18},
{"symbol":"PG","date":"2021-01-26","adj_close":133.09},
{"symbol":"HSY","date":"2021-01-26","adj_close":149.52},
{"symbol":"CLX","date":"2021-01-26","adj_close":212.99},
{"symbol":"COST","date":"2021-01-26","adj_close":364.98},
{"symbol":"MDLZ","date":"2021-01-26","adj_close":57.59},
{"symbol":"K","date":"2021-01-26","adj_close":60.92},
{"symbol":"KHC","date":"2021-01-26","adj_close":34.39},
{"symbol":"PEP","date":"2021-01-26","adj_close":141.8},
{"symbol":"PG","date":"2021-01-27","adj_close":128.38},
{"symbol":"HSY","date":"2021-01-27","adj_close":146.19},
{"symbol":"CLX","date":"2021-01-27","adj_close":222.18},
{"symbol":"COST","date":"2021-01-27","adj_close":356.39},
{"symbol":"MDLZ","date":"2021-01-27","adj_close":56.42},
{"symbol":"K","date":"2021-01-27","adj_close":62.36},
{"symbol":"KHC","date":"2021-01-27","adj_close":34.74},
{"symbol":"PEP","date":"2021-01-27","adj_close":138.04},
{"symbol":"PG","date":"2021-01-28","adj_close":130.36},
{"symbol":"HSY","date":"2021-01-28","adj_close":148.21},
{"symbol":"CLX","date":"2021-01-28","adj_close":209.57},
{"symbol":"COST","date":"2021-01-28","adj_close":357.06},
{"symbol":"MDLZ","date":"2021-01-28","adj_close":57.12},
{"symbol":"K","date":"2021-01-28","adj_close":60.17},
{"symbol":"KHC","date":"2021-01-28","adj_close":33.96},
{"symbol":"PEP","date":"2021-01-28","adj_close":139.19},
{"symbol":"PG","date":"2021-01-29","adj_close":128.21},
{"symbol":"HSY","date":"2021-01-29","adj_close":145.44},
{"symbol":"CLX","date":"2021-01-29","adj_close":209.46},
{"symbol":"COST","date":"2021-01-29","adj_close":352.43},
{"symbol":"MDLZ","date":"2021-01-29","adj_close":55.44},
{"symbol":"K","date":"2021-01-29","adj_close":58.94},
{"symbol":"KHC","date":"2021-01-29","adj_close":33.51},
{"symbol":"PEP","date":"2021-01-29","adj_close":136.57},
{"symbol":"PG","date":"2021-02-01","adj_close":128.97},
{"symbol":"HSY","date":"2021-02-01","adj_close":145.11},
{"symbol":"CLX","date":"2021-02-01","adj_close":210.02},
{"symbol":"COST","date":"2021-02-01","adj_close":350.52},
{"symbol":"MDLZ","date":"2021-02-01","adj_close":55.25},
{"symbol":"K","date":"2021-02-01","adj_close":58.82},
{"symbol":"KHC","date":"2021-02-01","adj_close":33.25},
{"symbol":"PEP","date":"2021-02-01","adj_close":136.98},
{"symbol":"PG","date":"2021-02-02","adj_close":128.79},
{"symbol":"HSY","date":"2021-02-02","adj_close":147.12},
{"symbol":"CLX","date":"2021-02-02","adj_close":204.23},
{"symbol":"COST","date":"2021-02-02","adj_close":355.58},
{"symbol":"MDLZ","date":"2021-02-02","adj_close":56.16},
{"symbol":"K","date":"2021-02-02","adj_close":58.45},
{"symbol":"KHC","date":"2021-02-02","adj_close":33.16},
{"symbol":"PEP","date":"2021-02-02","adj_close":138.38},
{"symbol":"PG","date":"2021-02-03","adj_close":128.95},
{"symbol":"HSY","date":"2021-02-03","adj_close":146.58},
{"symbol":"CLX","date":"2021-02-03","adj_close":204.59},
{"symbol":"COST","date":"2021-02-03","adj_close":355.21},
{"symbol":"MDLZ","date":"2021-02-03","adj_close":55.28},
{"symbol":"K","date":"2021-02-03","adj_close":58.01},
{"symbol":"KHC","date":"2021-02-03","adj_close":33.01},
{"symbol":"PEP","date":"2021-02-03","adj_close":138.02},
{"symbol":"PG","date":"2021-02-04","adj_close":129.03},
{"symbol":"HSY","date":"2021-02-04","adj_close":147.22},
{"symbol":"CLX","date":"2021-02-04","adj_close":191.65},
{"symbol":"COST","date":"2021-02-04","adj_close":355.85},
{"symbol":"MDLZ","date":"2021-02-04","adj_close":56},
{"symbol":"K","date":"2021-02-04","adj_close":57.87},
{"symbol":"KHC","date":"2021-02-04","adj_close":32.92},
{"symbol":"PEP","date":"2021-02-04","adj_close":139.68},
{"symbol":"PG","date":"2021-02-05","adj_close":129.57},
{"symbol":"HSY","date":"2021-02-05","adj_close":146.6},
{"symbol":"CLX","date":"2021-02-05","adj_close":191.25},
{"symbol":"COST","date":"2021-02-05","adj_close":355.17},
{"symbol":"MDLZ","date":"2021-02-05","adj_close":56.21},
{"symbol":"K","date":"2021-02-05","adj_close":58.03},
{"symbol":"KHC","date":"2021-02-05","adj_close":33.8},
{"symbol":"PEP","date":"2021-02-05","adj_close":140.96},
{"symbol":"PG","date":"2021-02-08","adj_close":129.17},
{"symbol":"HSY","date":"2021-02-08","adj_close":149.33},
{"symbol":"CLX","date":"2021-02-08","adj_close":190},
{"symbol":"COST","date":"2021-02-08","adj_close":359.83},
{"symbol":"MDLZ","date":"2021-02-08","adj_close":56.02},
{"symbol":"K","date":"2021-02-08","adj_close":57.74},
{"symbol":"KHC","date":"2021-02-08","adj_close":33.91},
{"symbol":"PEP","date":"2021-02-08","adj_close":140.4},
{"symbol":"PG","date":"2021-02-09","adj_close":128.67},
{"symbol":"HSY","date":"2021-02-09","adj_close":149.62},
{"symbol":"CLX","date":"2021-02-09","adj_close":187.35},
{"symbol":"COST","date":"2021-02-09","adj_close":359.56},
{"symbol":"MDLZ","date":"2021-02-09","adj_close":55.5},
{"symbol":"PEP","date":"2021-02-09","adj_close":139.6},
{"symbol":"KHC","date":"2021-02-09","adj_close":33.71},
{"symbol":"K","date":"2021-02-09","adj_close":57.64}]
Here is a sample including company ticker selector:
Presentator.js:
export function Presentator() {
const [data, setData] = useState([]);
const [ticker, setTicker] = useState('');
useEffect(() => {
const fetchData = async () => {
/* DO ACTUAL FETCH FROM SERVICE */
const result = await Promise.resolve(response);
setData(result);
}
fetchData();
}, []);
const handleTickerChange = (event) => {
setTicker(event.target.value);
}
const getTickerData = (ticker) => {
return data.filter(item => item.symbol.toLowerCase() === ticker.toLowerCase());
};
const getTickerDropdownValues = () => {
const set = new Set();
data.forEach(item => {
if (!set.has(item.symbol)) {
set.add(item.symbol);
}
});
return Array.from(set);
}
const getTickerDropdown = () => {
const options = getTickerDropdownValues();
return (
<select value={ticker} onChange={handleTickerChange}>
{options.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
);
}
return (
<>
{getTickerDropdown()}
<Graph data={getTickerData(ticker)} />
</>
);
}
Graph.js:
export function Graph(props) {
const { data } = props;
const getChartData = () => {
const labels = [];
const series = [];
data.forEach(item => {
labels.push(item.date);
series.push(item.adj_close);
});
return {
labels: labels,
series: [series]
};
}
// Add your graph configuration here
const chartOptions = {
// width: 2000,
height: 400,
// scaleMinSpace: 20
};
return (
<ChartistGraph data={getChartData()} options={chartOptions} type="Line" />
);
}
Basically, the Presentator handles the initial fetching of the data and the logic to split the data by ticker. Then, the Graph component handles the visualization of the specific ticker data itself.
You can check a working example at this codesandbox.
You don't need to store anything more in the state than the data itself. In our case we're also storing the selected value for the ticker dropdown. Everything else can be calculated.
In the getChartData function you can do further filtering and manipulation of the data as for example presenting only the last 10 records(dates) instead of the whole set.
If I understand you correctly, you need to display the adj_close values for each date, grouped by symbol. Is that correct?
First, make changes to your state:
const [chartData, setChartData] = useState({
labels: [],
series: []
});
You can group the response by symbol like this:
const symbols = response.reduce((map, value) => {
if (map.has(value.symbol)) {
map.set(value.symbol, [...map.get(value.symbol), value]);
} else {
map.set(value.symbol, [value]);
}
return map;
}, new Map())
Then get the unique dates:
const dates = [...new Set(response.map(r => r.date))]; // note: it doesn't sort dates!
Then construct the series multi-dimensional array. For each symbol, you include the adj_close values for every date.
const series = Array.from(symbols).map(value => {
const valuesForSymbol = value[1];
return dates.map(date => {
const valueForDate = valuesForSymbol.find(v => v.date === date);
return valueForDate.adj_close;
});
});
Set the state:
setChartData({labels: dates, series });
And finally, display the chart like this:
<ChartistGraph data={chartData} options={options} type="Line" />
Full example here.
I have rewritten you code check if its work for your situation
import React, { useState, useEffect } from "react";
import ChartistGraph from 'react-chartist';
export default function Graph() {
const [data, setData] = useState({
chart: {
label: [],
series: []
},
dataBySymbols: {},
symbols: [],
select: "",
});
const getData = () => {
setTimeout(() => {
const _tmp = new Set();
const dataBySymbols = {};
response.forEach(item => {
_tmp.add(item.symbol);
if (!dataBySymbols.hasOwnProperty(item.symbol)) {
dataBySymbols[item.symbol] = {
label: [],
series: [
[]
]
};
}
dataBySymbols[item.symbol]['label'].push(item.date);
dataBySymbols[item.symbol]['series'][0].push(item.adj_close);
});
const copy = {...data};
copy['dataBySymbols'] = dataBySymbols;
copy['symbols'] = Array.from(_tmp);
copy['chart'] = dataBySymbols[copy['symbols'][0]];
setData(copy);
}, 3000)
}
useEffect(() => {
getData()
}, [])
function onSelectChange(evt) {
const copy = {...data};
copy['select'] = evt.target.value;
copy['chart'] = copy.dataBySymbols[evt.target.value]
setData(copy);
}
const options = {
width: 500,
height: 400
};
return (
<div>
<select value={data.select} onChange={onSelectChange}>
{data.symbols.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
<ChartistGraph data={data.chart} options={options} type="Line" />
</div>
);
};
export default function App() {
return (
<Graph />
);
}
Here working example

Unexpected mutation of array in React

I am just learning to program and am writing one of my first applications in React. I am having trouble with an unexpected mutation that I cannot find the roots of. The snippet is part of a functional component and is as follows:
const players = props.gameList[gameIndex].players.map((item, index) => {
const readyPlayer = [];
props.gameList[gameIndex].players.forEach(item => {
readyPlayer.push({
id: item.id,
name: item.name,
ready: item.ready
})
})
console.log(readyPlayer);
readyPlayer[index].test = "test";
console.log(readyPlayer);
return (
<li key={item.id}>
{/* not relevant to the question */}
</li>
)
})
Now the problem is that readyPlayer seems to be mutated before it is supposed to. Both console.log's read the same exact thing. That is the array with the object inside having the test key as "test". forEach does not mutate the original array, and all the key values, that is id, name and ready, are primitives being either boolean or string. I am also not implementing any asynchronous actions here, so why do I get such an output? Any help would be greatly appreciated.
Below is the entire component for reference in its original composition ( here also the test key is replaced with the actual key I was needing, but the problem persists either way.
import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
// import styles from './Lobby.module.css';
const Lobby = ( props ) => {
const gameIndex = props.gameList.findIndex(item => item.id === props.current.id);
const isHost = props.gameList[gameIndex].hostId === props.user.uid;
const players = props.gameList[gameIndex].players.map((item, index) => {
const isPlayer = item.id === props.user.uid;
const withoutPlayer = [...props.gameList[gameIndex].players];
withoutPlayer.splice(index, 1);
const readyPlayer = [];
props.gameList[gameIndex].players.forEach(item => {
readyPlayer.push({
id: item.id,
name: item.name,
ready: item.ready
})
})
const isReady = readyPlayer[index].ready;
console.log(readyPlayer);
console.log(!isReady);
readyPlayer[index].ready = !isReady;
console.log(readyPlayer);
return (
<li key={item.id}>
{isHost && index !== 0 && <button onClick={() => props.updatePlayers(props.gameList[gameIndex].id, withoutPlayer)}>Kick Player</button>}
<p>{item.name}</p>
{isPlayer && <button onClick={() =>props.updatePlayers(props.gameList[gameIndex].id, readyPlayer)}>Ready</button>}
</li>
)
})
let showStart = props.gameList[gameIndex].players.length >= 2;
props.gameList[gameIndex].players.forEach(item => {
if (item.ready === false) {
showStart = false;
}
})
console.log(showStart);
return (
<main>
<div>
{showStart && <Link to="/gameboard" onClick={props.start}>Start Game</Link>}
<Link to="/main-menu">Go back to Main Menu</Link>
</div>
<div>
<h3>Players: {props.gameList[gameIndex].players.length}/4</h3>
{players}
</div>
</main>
);
}
Lobby.propTypes = {
start: PropTypes.func.isRequired,
current: PropTypes.object.isRequired,
gameList: PropTypes.array.isRequired,
updatePlayers: PropTypes.func.isRequired,
user: PropTypes.object.isRequired
}
export default Lobby;
Note: I did manage to make the component actually do what it is supposed, but the aforementioned unexpected mutation persists and is still a mystery to me.
I have created a basic working example using the code snippet you provided. Both console.log statements return a different value here. The first one returns readyPlayer.test as undefined, the second one as "test". Are you certain that the issue happens within your code snippet? Or am I missing something?
(Note: This answer should be a comment, but I am unable to create a code snippet in comments.)
const players = [
{
id: 0,
name: "John",
ready: false,
},
{
id: 1,
name: "Jack",
ready: false,
},
{
id: 2,
name: "Eric",
ready: false
}
];
players.map((player, index) => {
const readyPlayer = [];
players.forEach((item)=> {
readyPlayer.push({
id: item.id,
name: item.name,
ready: item.ready
});
});
// console.log(`${index}:${readyPlayer[index].test}`);
readyPlayer[index].test = "test";
// console.log(`${index}:${readyPlayer[index].test}`);
});
console.log(players)

How to fix "TypeError: results.map is not a function", in React

function Results(props) {
var results = props.results;
return (
<>
<table>
<thead>
<tr>
<th>Book Name</th>
<th>Author</th>
<th>S.no</th>
<th>Series Name</th>
<th>Type</th>
<th>Genre</th>
<th>Kindle/Real</th>
</tr>
</thead>
<tbody>
{results.map(result => {
return (
<tr key={result.name}>
<td>{result.name}</td>
<td>{result.author}</td>
<td>{result.sno}</td>
<td>{result.series}</td>
<td>{result.type}</td>
<td>{result.genre}</td>
<td>{result.kindeReal}</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
When I try to render the above com component, I get the error:
TypeError: results.map is not a function
The results variable is an array of objects, something like:
[{"type":1},{"type":0},{"type":2}]
However, when I use the .map function, it returns the error! It is clearly an array, so why can't I use it?
This is the output of console.log(results).
[{"Book_Name":"Time Riders","Author":"Alex Scarrow","S_no":1,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"Day of the Predator ","Author":"Alex Scarrow","S_no":2,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"The Doomsday Code","Author":"Alex Scarrow","S_no":3,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"The Eternal War","Author":"Alex Scarrow","S_no":4,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"Gates of Rome","Author":"Alex Scarrow","S_no":5,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"City of Shadows","Author":"Alex Scarrow","S_no":6,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"The Pirate Kings","Author":"Alex Scarrow","S_no":7,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"The Mayan Prophecy","Author":"Alex Scarrow","S_no":8,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"},{"Book_Name":"The Infinity Cage","Author":"Alex Scarrow","S_no":9,"Series_Name":"Time Riders","Fiction_Non_fiction_Companion_Prequel":"Fiction","Genre":"Sci-fi/Mystery/Thriller","Kindle_Real":"Real"}]
It looks like an array to me. Why is it not an array then?
This is the parent component.
import React from "react";
import Results from "./results";
function ResultsRenderer(props) {
if (props.status === true) {
return <Results results={props.results} />;
} else {
return <>{"No"}</>;
}
}
export default ResultsRenderer;
This is the parent component of ResultsRenderer.
import React, { useState } from "react";
import { useEffect } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Form from "./searcherFormDumb";
import { toast } from "react-toastify";
import ResultsRenderer from "./resultsRenderer";
function Searcher() {
const [answer, setAnswer] = useState(["Empty", false]);
const [book, setBook] = useState({
name: "",
author: "",
sno: null,
series: "",
type: "",
genre: "",
kindleReal: ""
});
const defaultState = {
name: "",
author: "",
sno: null,
series: "",
type: "",
genre: "",
kindleReal: ""
};
function handleChange(event) {
const updatedBook = { ...book, [event.target.name]: event.target.value };
setBook(updatedBook);
}
function handleSubmit(event) {
event.preventDefault();
var changed = {};
function populateChanged(now, old, title, temp) {
if (now !== old) {
temp[title] = now;
return temp;
} else {
return temp;
}
}
changed = populateChanged(
book.name,
defaultState.name,
"Book_Name",
changed
);
changed = populateChanged(
book.author,
defaultState.author,
"Author",
changed
);
changed = populateChanged(book.sno, defaultState.sno, "S_no", changed);
changed = populateChanged(
book.series,
defaultState.series,
"Series_Name",
changed
);
changed = populateChanged(
book.type,
defaultState.type,
"Fiction_Non_fiction_Companion_Prequel",
changed
);
changed = populateChanged(book.genre, defaultState.genre, "Genre", changed);
changed = populateChanged(
book.kindleReal,
defaultState.kindleReal,
"Kindle_Real",
changed
);
var temp_string = "";
var key = "";
var value = "";
var temp_string_list = [];
//debugger;
for (var i = 0; i < Object.keys(changed).length; i++) {
//debugger;
key = Object.keys(changed)[i];
value = changed[key];
if (i !== Object.keys(changed).length - 1) {
temp_string = `${key} = "${value}" AND `;
} else if (i === Object.keys(changed).length - 1) {
temp_string = `${key} = "${value}"`;
}
temp_string_list.push(temp_string);
//debugger;
temp_string = "";
key = "";
value = "";
}
var sql_t = temp_string_list.join("");
var sql_tt = "SELECT * FROM books_catalouge WHERE ";
var sql = sql_tt + sql_t;
toast.success(sql);
var request = new XMLHttpRequest();
var jsql = JSON.stringify(sql);
request.onreadystatechange = function() {
//debugger;
if (this.readyState == 4 && this.status == 200) {
setAnswer([this.responseText, true]);
console.log(`${answer}`);
}
};
request.open(
"GET",
"http://localhost:3001/retrieve_books" + "?msg=" + jsql,
true
);
request.send(jsql);
console.log("This is the END");
console.log(`${answer}`);
}
return (
<>
<Form book={book} onChange={handleChange} onSubmit={handleSubmit} />
<br />
<ResultsRenderer status={answer[1]} results={answer[0]} />
</>
);
}
export default Searcher;
Let me know if you need the NodeJS as well. I am using SQL to get the data, which is why I need the NodeJS. Sorry if my code is a little weird.
Thanks in advance!
Function map() can be used only on array. In this situation it looks like props.results is not array or has not been set yet (this can happen if you are fetching data with Axios or something like that).
I would recommend you to place something like this at the start of function:
if (!props.results) return 'no data';
if (!Array.isArray(props.results)) return 'results are not array'
after clarification
You get response on your onreadystatechange request which usualy comes in JSON or XML. I think your answer is stringified json. Try to use JSON.parse(response) in case of JSON or (new DOMParser()).parseFromString(response,"text/xml") in case of XML.
In your component it may look like this
request.onreadystatechange = function() {
(this.readyState == 4 && this.status == 200)
&& setAnswer([JSON.parse(this.responseText), true]);
};
I'm seeing similar behavior when deserializing a simple .json file:
const stringifiedData = fs.readFileSync(animalsPath);
const animalData = JSON.parse(stringifiedData);
const animals = animalData.map(animal => {
return new Animal(animal)
})
Oddly, the example I'm following is doing a string dot notation that seems to satisfy V8 that the object is an array, even though it's output in console.out does not change. The following does work but I don't know why. Any ideas?
const stringifiedData = fs.readFileSync(animalsPath);
const animalData = JSON.parse(stringifiedData).animals;
const animals = animalData.map(animal => {
return new Animal(animal)
})
I also got the same error while accessing data element of an array. here is what I did:
{standardObj ? (
{standardObj.map((obj: any) => {
return (
<Grid item>
<FormControlLabel
className={styles.CheckboxLabel}
key={obj.Code}
control={
<Checkbox
onChange={handleCheckElement}
name={obj.FullName}
value={obj.Code}
/>
}
label={obj.FullName}
/>
</Grid>
);
})}
) : null }
I faced the same problem and appars that for the useState Hook is very important the type of data of the inital value, I had as initial value a 0 int and cos that react didn't recognize the update as array.
I am new to React and found out that if a variable is empty / undefined and used with "map" function, the React throws that exception. My solution was to check a variable for "undefined" and length > 0.
Most of the time this problem is because of wrong syntax.
where there is
results.map(result => {
........................
}
just do
results.map(result => (
........................
)

Categories