How to create multiple line charts from a single component in React - reactjs

I am trying to create multiple line charts from a single component in react and seem to be getting lost a big.
My API is giving me back data that looks like this.
[
{
"price": 6500,
"expiration": "10",
"bid": 86.44,
"mark": 89.74,
"ask": 95.94,
"dif": -0.01575
},
{
"price": 6750,
"expiration": "10",
"bid": 74.09,
"mark": 78.77,
"ask": 82.52,
"dif": -0.02023
},
{
"price": 7000,
"expiration": "20",
"bid": 69.28,
"mark": 70.67,
"ask": 74.62,
"dif": -0.03171
},
{
"price": 7250,
"expiration": "20",
"bid": 68.06,
"mark": 67.44,
"ask": 71.08,
"dif": -0.06388
}
]
What I am trying to do is to create a component that will take this data and map it to two separate line charts using Chart.Js.
Each chart should be broken out by expiration. With the X-axis being price and the Y-axis is supposed to be mark. I have found a good example implementing close to what I want to do here --> How to map multiple charts with chart.js in react
But I want to create 2 charts from this data. Where the charts are grouped by Expiration. I am not sure what I am missing from the example above that I would need to change to do this. Any help would be amazing.
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Line } from "react-chartjs-2";
import axios from "axios";
export default class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: [],
data: []
};
}
componentDidMount() {
fetch(API, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({query: query}),
})
.then(res => res.json())
.then(
(res)=>{
const x = res.data;
let chartData = [];
x.forEach(element => {
chartData.push({
labels: element.expiration,
datasets: [{ data: element.price}]
});
});
this.setState({ chartData });
});
}
render() {
return (
<div className="chart">
{this.state.chartData.map((n, index) => {
return <Line key={index} data={n} />;
})}
</div>
);
}
}

Related

React rest call map result to selectbox with avatar and label per option

Hi here is rest response:
[
{
"self": "https://your-domain.atlassian.net/rest/api/3/project/EX",
"id": "10000",
"key": "EX",
"name": "Example",
"avatarUrls": {
"48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10000",
"24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10000",
"16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10000",
"32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10000"
},
"projectCategory": {
"self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
"id": "10000",
"name": "FIRST",
"description": "First Project Category"
},
"simplified": false,
"style": "classic",
"insight": {
"totalIssueCount": 100,
"lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
}
},
{
"self": "https://your-domain.atlassian.net/rest/api/3/project/ABC",
"id": "10001",
"key": "ABC",
"name": "Alphabetical",
"avatarUrls": {
"48x48": "https://your-domain.atlassian.net/secure/projectavatar?size=large&pid=10001",
"24x24": "https://your-domain.atlassian.net/secure/projectavatar?size=small&pid=10001",
"16x16": "https://your-domain.atlassian.net/secure/projectavatar?size=xsmall&pid=10001",
"32x32": "https://your-domain.atlassian.net/secure/projectavatar?size=medium&pid=10001"
},
"projectCategory": {
"self": "https://your-domain.atlassian.net/rest/api/3/projectCategory/10000",
"id": "10000",
"name": "FIRST",
"description": "First Project Category"
},
"simplified": false,
"style": "classic",
"insight": {
"totalIssueCount": 100,
"lastIssueUpdateTime": "2022-12-08T07:09:19.702+0000"
}
}
]
I want to make select bobx having
<option value={data.id}><Img {data.16x16}/>data.label</option>
But result would be all projects if company has multiple projects so select box values have to map or loop into react
<Select options="result">
Im stuck as my code displays only label not any image there.
Another problem is that using data.avatarUrls.16x16 does not compile. VSCode says expecting "," and puts red underline to 16x16
Here is my code a lot is broken here because I have tested a lot ways but no luck
import React, { useState } from 'react';
import Select from 'react-select'
import { components } from 'react-select';
//Kun selectbox
const handleChange = event => {
//console.log(event.target.value);
setSelected(event.target.value);
};
//Palauttaa projectit json taulukon
const getProjects = async () => {
//Matti tähän sitten atlasion cmpany projection haku
const response = await api.asUser().requestJira(route`/rest/api/3/project`, {
headers: {
'Accept': 'application/json'
}
});
const data = await response.json();
//Mapataa hausta tarvittavat tiedot
const result = data.map(function (item, i) {
console.log('test');
return [
{
label: item.name,
value: item.id,
avatar: item.avatarUrls.16x16
}
]
})
return result
}
function Projects() {
//haetaan atlasiansita projectit array
const p = getProjects
//asetetaan state selectbox muutokselle
const [selected, setSelected] = useState(p.id);
return (
<div className='projects'>
<Select
className='select-projects'
options={p}
onChange={handleChange}
/>
</div>
);
}
export default Projects

React Apex Chart Data, Image and API

How to modify series and options, i want to make chart type=treemap on react hooks like this
i have name, user and percent on api.
{
"data": [
{
"id": "1",
"name": "Pisces",
"user": "95",
"percent": "3.15%",
},
{
"id": "2",
"name": "Leo",
"user": "50",
"percent": "2.35%",
},
{
"id": "3",
"name": "Capricorn",
"user": "91",
"percent": "3.12%",
}
]
}
and source for apex https://apexcharts.com/docs/chart-types/treemap-chart/
import React, { useState,useEffect } from 'react';
import axios from 'axios';
import './App.css';
import Chart from 'react-apexcharts'
import icUser from './image/profile-user.png'
import icChart from './image/pie-chart.png'
const App =()=> {
const [dataUser,setDataUser]=useState([])
useEffect(() => {
axios.get("http://localhost:4000/data")
.then(response =>{
setDataUser(response.data)
}).catch(e => {
alert(e);
})
}, [])
const series = {.....}
const options = {.....}
return (
<div>
<Chart options={options} series={series} height={350} type="treemap"/>
</div>
)
}
export default App
In series you need to pass an array like this, Where x is the name, and y percentage. and In option you can modify the treemap chart like change height, type, plotOptions and more...
const App = () => {
const [dataUser, setDataUser] = useState([])
useEffect(() => {
axios.get("http://localhost:4000/data")
.then(response => {
setDataUser(response.data)
}).catch(e => {
alert(e);
})
}, [])
const seriesData = [];
const options = {}
dataUser.map((val) => {
seriesData.push(
{
x: val.name, //
y: val.percent //
}
);
});
const series = [{ data: seriesData }];
return (
<div>
<Chart options={options} series={series} height={350} type="treemap" />
</div>
)
}
export default App

How to get array format value in json using reactjs?

I added my coding's for how to create state like at the end of this question above coding's are i will try but am not able to create like that state.
This is my json format coding to get through
"Results": {
"Piechart":[{
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [{
"data": [2000, 4000, 2850],
"backgroundColor": ["red", "blue", "green"]
}]
}]
}
Here is my React Code
this.state = {labels: [], datasets: []};
componentDidMount() {
this.pieChart().then(result => {
this.setState({diagramData: result.pieDiagramLabel});
}).catch(err => console.error(err));
}
async pieChart() {
let pieChart = await import('../data/result_log.json');
console.log(pieChart[0].Results.Piechart);
return {
pieDiagramLabel: pieChart[0].Results.Piechart.labels
}
}
How to get both label and datasets? And how to set into state like below format
this.state= {
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [{
"data": [2000, 4000, 2850],
}]
}
You can try like this
data.json
{
"Piechart": [
{
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [
{
"data": [2000, 4000, 2850],
"backgroundColor": ["red", "blue", "green"]
}
]
}
]
}
App.js
import React from "react";
import Results from "./data.json";
export default class App extends React.Component {
state = {
labels: [],
datasets: []
};
componentDidMount() {
this.setState({
labels: Results.Piechart[0].labels,
datasets: Results.Piechart[0].datasets
});
}
render() {
const { labels, datasets } = this.state;
return (
<div className="App">
{labels.map((label, index) => (
<p key={index}>{label}</p>
))}
<hr />
{datasets.map((data, index) => (
<p key={index}>{data.backgroundColor}</p>
))}
</div>
);
}
}
Live working demo https://codesandbox.io/s/fetch-local-json-6bq4m

How to list incoming data in React Native

I want to list the data from the service I use as it is in the example. Can you help me?
My code:
import React, { Component } from "react";
export default class CustomersTab extends Component {
constructor(props) {
super(props);
this.state = {
token: "",
isLoading: true,
dataSource: null
};
}
componentWillMount() {
tokenner()
.then(responseJson => {
const token = "Bearer " + responseJson.result.token;
this.setState({ token });
fetch(
"apiurl",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: token
}
}
)
.then(response => response.json())
.then(responseData => {
this.setState({
isLoading: false,
dataSource: responseData.result
});
});
})
.catch(error => console.warn(error));
}};
render() {
return (
<View>
<Text>
I WANT LİST DATA HERE
</Text>
</View> )}}
I tried to do it myself, but I could not build the loop structure. Only one data is displayed every time. What should I do?
you have to do something like this. Change id to what you want to display.
return (
<View>
<ListView
dataSource={this.state.dataSource}
renderRow={data => <Text>{data.id}</Text>}
/>
</View>
);
Please Import the View and Text from react native.
import {
Text,
View,
} from 'react-native';
constructor(props: Object) {
super(props);
this.state = {
dataSource: []
}
};
/* dataSource = [
{ "id": "1", "title": "Star Wars", "releaseYear": "1977" },
{ "id": "2", "title": "Back to the Future", "releaseYear": "1985" },
{ "id": "3", "title": "The Matrix", "releaseYear": "1999" },
{ "id": "4", "title": "Inception", "releaseYear": "2010" },
{ "id": "5", "title": "Interstellar", "releaseYear": "2014" }
]
*/
renderMovieList(){
return this.state.dataSource.map((movie, index) =>
<View
key={movie.id}
style={{ height:50 padding:10}}>
<Text> movie.title</Text>
<Text> movie.releaseYear</Text>
</View>
)
}
render() {
return (
<View style={{flex: 1, justifyContent:'center'}}>
{this.state.dataSource.length ? this.renderMovieList(): null}
</View>
);
}

Rendering a nested object state

This problem is giving me a huge headache so any help is welcome :)
In this component, I'm making 2 axios calls to different APIs: one for freegeoip and one for openweathermap. I'm storing the data in the currentCity state, which is an object with 2 keys, location and weather. The idea is that the app detects your current location (using freegeoip) and renders location name and weather data (using openweathermap).
I'm positive it's storing the state properly as console logs have confirmed. I can render the location data for currentCity state, but can't seem to render the weather data for currentCity state.
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li> // Working
<li>{city.weather.main.temp}</li> // Not working
</div>
)
}
The console error I get:
Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null
currentCity.location JSON:
{
"ip": // hidden,
"country_code": "FR",
"country_name": "France",
"region_code": "GES",
"region_name": "Grand-Est",
"city": "Reims",
"zip_code": "",
"time_zone": "Europe/Paris",
"latitude": 49.25,
"longitude": 4.0333,
"metro_code": 0
}
currentCity.weather JSON:
{
"coord": {
"lon": 4.03,
"lat": 49.25
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 283.15,
"pressure": 1011,
"humidity": 43,
"temp_min": 283.15,
"temp_max": 283.15
},
"visibility": 10000,
"wind": {
"speed": 3.1,
"deg": 350
},
"clouds": {
"all": 0
},
"dt": 1493127000,
"sys": {
"type": 1,
"id": 5604,
"message": 0.1534,
"country": "FR",
"sunrise": 1493094714,
"sunset": 1493146351
},
"id": 2984114,
"name": "Reims",
"cod": 200
}
Rest of code:
import React, { Component } from 'react';
import axios from 'axios';
import WeatherList from './weatherlist';
import SearchBar from './searchbar';
const API_KEY = '95108d63b7f0cf597d80c6d17c8010e0';
const ROOT_URL = 'http://api.openweathermap.org/data/2.5/weather?'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
cities: [],
errors: '',
currentCity: {
location: {},
weather: {}
}
};
this.currentCity();
this.renderCurrentCity = this.renderCurrentCity.bind(this);
}
citySearch(city) {
const url = `${ROOT_URL}&appid=${API_KEY}&q=${city}`;
axios.get(url)
.then(response => {
const citiesArr = this.state.cities.slice();
this.setState({
cities: [response.data, ...citiesArr],
errors: null
});
})
.catch(error => {
this.setState({
errors: 'City not found'
})
})
}
currentCity() {
var city;
var country;
axios.get('http://freegeoip.net/json/')
.then(response => {
const lat = response.data.latitude;
const lon = response.data.longitude;
city = response.data.city;
country = response.data.country_name;
const url = `${ROOT_URL}&appid=${API_KEY}&lat=${lat}&lon=${lon}`;
const state = this.state.currentCity;
console.log('state1:',state);
this.setState({
currentCity: { ...state, location: response.data }
});
console.log(url);
axios.get(url)
.then(city => {
const state = this.state.currentCity;
console.log('state2:', state);
this.setState({
currentCity: { ...state, weather: city.data }
});
})
})
}
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li>
<li>{city.weather.main.temp}</li>
</div>
)
}
render() {
return (
<div className={this.state.cities == false ? 'search': 'search-up'}>
<h1>What's the weather today?</h1>
<ul className='list-unstyled text-center'>
{this.renderCurrentCity(this.state.currentCity)}
</ul>
<SearchBar
onSearchSubmit={this.citySearch.bind(this)}
errors={this.state.errors} />
{this.state.cities == false ? null : <WeatherList cities={this.state.cities} />}
</div>
)
}
}
You are spreading your whole state when your receive the weather data:
this.setState({
currentCity: { ...state, weather: city.data }
});
it should be:
this.setState({
currentCity: { ...state.currentCity, weather: city.data }
});

Resources