reaching data inside an object while using map - node.js

I'm sorry in advance for my ignorance, But its been a while since I coded, and I need a little help with this basic thing, Im trying to reach name, and display it on screen when I click a button, but i just can't figure it out, can u help me and explain what you did so I can know for the next time? looked manuals and articles about how to do it but you guys are just simply better.
my code:
functional (pokeAPI.ts):
import React from "react";
import axios from 'axios'
export const getPokemon=()=>{
axios.get("https://pokeapi.co/api/v2/pokemon?limit=151").then((response)=>{
response.data.results.map((cont : string,index : number) => console.log(
cont
));
})
}
app.tsx:
import './App.css';
import React from 'react';
import {getPokemon} from './func/pokeAPI';
function App() {
return (
<div>
<button onClick={getPokemon}>Cli</button>
</div>
);
}
export default App;

Here you go! Since you're using typescript, I created a PokemonData interface as well.
import React from 'react'
import axios from 'axios'
import "./styles.css";
interface PokemonData {
name: string
url: string
}
export default function App() {
const [pokemons, setPokemons] = React.useState<null|PokemonData[]>(null)
const onClick = async () => {
axios.get("https://pokeapi.co/api/v2/pokemon?limit=151").then((response)=>{
console.log(response.data.results)
setPokemons(response.data.results)
})
}
return (
<div className="App">
<button onClick={onClick}>Get pokemon</button>
{pokemons?.map((pokemon) => (
<div key={pokemon.name}>
<p>{pokemon.name}</p>
<p>{pokemon.url}</p>
</div>
))}
</div>
);
}
I also wrote a Codesandbox here so you can check it out
Edit: Another version of the return statement if optional chaining isn't supported on your project's version
return (
<div className="App">
<button onClick={onClick}>Get pokemon</button>
{pokemons && pokemons.map((pokemon) => (
<div key={pokemon.name}>
<p>{pokemon.name}</p>
<p>{pokemon.url}</p>
</div>
))}
</div>
);
}

Related

What is console.error in react testing and is it okay to ignore?

I am on the way to learning Jest and React Testing Library.
When I run the test below, it is 'passed' but I see the console.error message.
[sectionIntro.spec.js]
import React from "react";
import { fireEvent, render, screen } from "#testing-library/react";
import SectionIntro from "../../components/home/SectionIntro.jsx";
import { CV_URL } from "../../lib/socials";
describe("SectionIntroComponent", () => {
it("Should open the CV link when CV button is clicked", () => {
render(<SectionIntro />);
const cv_link = screen.getByText(/Check My CV/i);
expect(cv_link.href).toBe(CV_URL);
});
});
// Also a mock file is used for an image file.
[SectionIntro.jsx]
import * as React from "react";
import Image from "next/image";
import profilePic from "../../public/me.png";
import styles from "../../styles/SectionIntro.module.css";
import { CV_URL } from "../../lib/socials";
const SectionIntro = () => {
return (
<>
<div>
<div>
<Image
className="rounded-full"
src={profilePic}
alt="The author of the website"
objectFit="cover"
sizes="30vw"
/>
</div>
</div>
<div>
<button
className={`${styles.btnCV}`}
>
<a
href={CV_URL}
aria-label="CV"
target="_blank"
rel="noopener noreferrer"
>
Check My CV
</a>
</button>
</div>
</>
);
};
export default SectionIntro;
[mocks/mockFile.js]
export default "";
My question is if the test result is passed why the console.error is shown?
Would it be okay to ignore console.error?
If it is not a good idea to hide the console, why is it so?
Thanks alot in advance!

Monitoring multiple server stats in React JS

I have multiple pods running on my Kubernetes cluster and I have a "core app" built with react from which I want to get CPU & Memory usage stats.
Right now I am testing using a very simple setup where I have a local node app using socket.io to stream the time (based on this tutorial)
However, with one component which looks like the following, I am able to get real time updates from the server.
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
import {StatsCPUWrapper} from './statsCPU.style'
const ENDPOINT = process.env.STATS_ENDPOINT || "http://127.0.0.1:4001";
function StatsCPUComp() {
const [cpustats, setCPUstats] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("FromAPI", data => {
setCPUstats(data);
});
// Clean up the effect
return () => socket.disconnect();
}, []);
return (
<StatsCPUWrapper>
<p>
It's <time dateTime={cpustats}>{cpustats}</time>
</p>
</StatsCPUWrapper>
);
}
export default StatsCPUComp;
What I am now trying to do is have 3 or more of those components (depends on the list I get from my backend) to "subscribe" to multiple servers at the same time.
Here's my "projects list" component which gets the stats from the initial state and renders all the details:
import React from 'react'
import {useSelector, useDispatch} from 'react-redux'
import {Link} from 'react-router-dom'
import PropTypes from 'prop-types'
import {create, remove} from '../../features/projects/projectSlice'
import {ProjectWrapper} from './project.style'
import StatsCPUComp from './stats/statsCPU'
export function ProjectComp() {
const dispatch = useDispatch()
const projects = useSelector((state) => state.projects)
const handleSubmit = (e) => {
e.preventDefault()
}
const handleAction = (e) => {
e.preventDefault()
}
return (
<ProjectWrapper>
<div className="projects">
<div className="row">
{projects.map((projects) => (
<div className="col-12">
<div class="card project-card">
<div className="card-body">
<div className="row">
<div className="col-4 project-text">
<h5 class="card-title">
{' '}
<Link to={`/projects/` + projects.id}>{projects.name}</Link>
</h5>
<p class="card-text">Owner: {projects.owner}</p>
<p class="card-text">{projects.email}</p>
</div>
<div className="col-4 projects-stats">
<StatsCPUComp />
</div>
<div className="col-4 projects-stats"></div>
<div className="col-4 projects-stats"></div>
</div>
</div>
</div>
<br></br>
</div>
))}
</div>
</div>
</ProjectWrapper>
)
}
Right now the "time" from the stats component is being added on my last project component (makes sense since I did not implement any approach yet to map that too).
Any ideas on how I can have a different stats component for each of my "projects" where each one connects to a provided endpoint ? (I can pass all of the endpoints as env variables)
Any help would be highly appreciated.
So here's the implementation I did to make it work. (Not sure if it's ideal so please feel free to make any suggestions)
I added "endpoint" to state.projects which holds the data I get from my backend.
Then in my "projects list" component mentioned shown in the question, I pass projects (from state.projects) as props
<StatsCPUComp props={projects}/>
I then destructure it and pass it to my useEffect() in the stats component as follows:
import React, {useState, useEffect} from 'react'
import socketIOClient from 'socket.io-client'
import {StatsCPUWrapper} from './statsCPU.style'
import {useSelector, useDispatch} from 'react-redux'
let ENDPOINTS = []
let PROJECTS = []
function StatsCPUComp(...props) {
const [cpustats, setCPUstats] = useState('')
let endpoints = {...props}
let endpoints_2 = {...endpoints[0]}
useEffect(() => {
let socketlist = []
console.log(endpoints[0].props.endpoint)
const socket = socketIOClient(endpoints[0].props.endpoint);
socket.on("FromAPI", data => {
setCPUstats(data);
});
return () => socket.disconnect();
}, [cpustats])
return (
<>
<StatsCPUWrapper>
<p>
It's <time dateTime={cpustats}>{cpustats}</time>
</p>
</StatsCPUWrapper>
</>
)
}
export default StatsCPUComp
It seems to be working fine, however please do provide any suggestions since I might not be following an optimal approach (Performance and scalability wise)

How to display images in Bootstrap carousel using React

So I have a component(Posts) in which a loop through all the posts from the Database. In the component, I 'embedded' another component(PostItem) so I dont have to create a different component for viewing individual entries. Now inside the PostItem component I have another component with the name of 'PostGallery'.
This is the current code that I have in PostItem.js file:
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PostGallery from '../posts/PostGallery';
const PostItem = ({
post: { _id, text, name, files, avatar, user, likes, comments, date },
}) => (
<article className={_id}>
<Link to={`/posts/${_id}`}>
<div id="carouselExampleIndicators" className="carousel slide" data-ride="carousel">
<div className="carousel-inner">
{files.slice(0, 5).map((file, index) => (
<PostGallery key={index} post={file} />
))}
</div>
</div>
</Link>
</article>
);
PostItem.propTypes = {
post: PropTypes.object.isRequired,
};
export default connect(
null, null
)(PostItem);
When posting an entry the user can post URL from images separated by comma which is working just fine. The problem comes when displaying it in the front-end.
This is what I have in my PostGallery component:
import React from 'react';
import PropTypes from 'prop-types';
const PostGallery = ({
post: { files }
}) => {
return (
<div className="">
{post.files.length > 0 ? (
post.files.map(file => (
<img key={file} src={file} alt="" />
))) : (
<p>No images found</p>
)
}
</div>
);
};
PostGallery.propTypes = {
post: PropTypes.object.isRequired,
};
export default PostGallery;
I believe this should be easy but somehow its just now working and the console it's not trowing me any errors related to it. So if you guys can help...
Thanks!

props can not be resolved in the render of a React class

I am getting started on webdevelopment with React and Node.js, all are new to me so I am following this tutorial: https://reactjs.org/tutorial/tutorial.html. I am using Visual Studio as IDE.
Everything seems to go as expected until I try to pass data through props. At that point "props" becomes flagged with an error "Cannot resolve symbol 'props'. I have googled myself silly trying to find a solution.
So far I have tried:
import React instead of declaring it as variable. Gives another error: Symbol 'React' cannot be properly resolved, probably it is located in inaccessible module
create a constructor. Gives another error: Call target does not contain any signatures.
Installed npm package for prop-types
I have posted my question to the relevant discord
So at this point I turn to you all, can you help me get going? See my code below:
declare var require: any;
var React = require('react');
var ReactDOM = require('react-dom');
//import * as React from "react";
//import * as ReactDOM from "react-dom";
//node_modules\.bin\webpack app.tsx --config webpack-config.js
class Square extends React.Component<any, any> {
//constructor() {
// super();
//}
render() {
return (
<button className="square">
{this.props.value}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square value={i}/>;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);

How do I use properly PropTypes on React 15.6.0?

I'm starting to work with react and redux, but I'm still a little lost about how to handle props and states.
I'm getting this type error:
TypeError: Cannot read property 'touched' of undefined
{name.touched && name.error && <div className="EmployeeForm-error">{name.error}</div>}
Could someone point me in the right direction or make me know what I'm doing wrong
EmployeeFormComponent.js:
import React from 'react';
import { reduxForm } from 'redux-form';
const EmployeeForm = ({ addEmployee, fields: {name}, handleSubmit }) => {
return (
<form onSubmit={handleSubmit(addEmployee)} >
<div>
<input
type="text"
placeholder="Name"
{...name}
/>
{name.touched && name.error && <div className="EmployeeForm-error">{name.error}</div>}
</div>
...
</form>
);}
export default reduxForm({
form: 'employee',
fields: ['name'],
validate,
})(EmployeeForm);
EmployeeFormContainer.js
import { connect } from 'react-redux';
import EmployeeForm from './EmployeeFormComponent';
import React from 'react';
class EmployeeFormContainer extends React.Component {
render() {
return (
<EmployeeForm {...this.props}/>
)
}
}
To solve it I modified a little my previous changing it to this, now I'm using redux-form Field, and sending the input on component attribute.
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
<div>
<input {...input} placeholder={label} type={type}/>
{touched && error && <div className="EmployeeForm-error">{error}</div>}
</div>
)
const EmployeeForm = ({ addEmployee, fields: { name, surname}, handleSubmit }) => {
return (
<form onSubmit={handleSubmit(addEmployee)}>
<div>
<Field name="name" type="text" component={renderField} label="name"/>
</div>
...
</form>
);}

Resources