Typescript Property '' does not exist on type 'never'. in React NodeJs stack - node.js

I am slowly teaching myself NodeJs, Express, React, monogoDB and Typescript.. (coming from a MVC C# SQL DB Background)
My very simple Hello world program just needs to communicate with the Express server to display a list of Users. My Express server is on Port 3001 and my Create-React-App Front end is on Port 3000.
my App Component is as follows:
import * as React from 'react';
import './App.css';
const logo = require('./logo.svg');
class App extends React.Component {
state = {users: []}
componentDidMount(){
console.log("Fetching Users");
fetch('/users')
.then(res=> res.json())
.then(users=> this.setState({users}));
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React test</h2>
{this.state.users.map(user =>
<div key={user.id}>{user.username}</div>
)}
</div>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}
export default App;
The error:
(21,28): error TS2339: Property 'id' does not exist on type 'never'.
I can see the problem is that I havent defined users to include properties users.id and users.username.. But I am unsure how to do this?

I may have posted this question a bit to quickly.
but I solved my answer
import * as React from 'react';
import './App.css';
const logo = require('./logo.svg');
interface Iuser {
id: number,
username: string
}
class App extends React.Component {
state = {users: Array<Iuser>()}
componentDidMount(){
console.log("Fetching Users");
fetch('/users')
.then(res=> res.json())
.then(users=> this.setState({users}));
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React test</h2>
{this.state.users.map(user =>
<div key={user.id}>{user.username}</div>
)}
</div>
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}
export default App;
(Creating an interface for the array object)
I did try this previously but had the syntax wrong.

Related

reaching data inside an object while using map

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>
);
}

Nextjs: Cant render a component while using map over a array of objects. Objects are not valid as a React child

I dont know why when i want to render a component inside of a map function, basiclly i have a List component, and when i fetch data from an API with the email, etc.. from users i want that component to render that info. But i get the following error:
Unhandled Runtime Error
Error: Objects are not valid as a React child (found: object with keys {email, phone, nick}). If you meant to render a collection of children, use an array instead.
My List component looks like this:
import React from 'react'
export default function List(email, nick, phone) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{email}</p>
<strong>Nick: </strong>
<p>{nick}</p>
<strong>Phone: </strong>
<p>{phone}</p>
</div>
)
}
And my List user page looks like this:
import React from 'react'
import Nav from '../../components/Nav/Nav'
import { useEffect, useState } from 'react';
import List from '../../components/User/List';
export default function index() {
const [users, setUsers] = useState([])
const fetchUsers = async () => {
const response = await fetch("http://localhost:3001/api/internal/users");
const data = await response.json();
console.log(data["data"])
setUsers(data["data"])
}
useEffect(() => {
fetchUsers()
}, [])
return (
<div>
<Nav />
{users.map(user => (
<List
email={user.attributes.email}
phone={user.attributes.phone}
nick={user.attributes.nick}
/>
))}
</div>
)
}
UPDATE 21 ABR
For some reason when i do this :
export default function List(email, phone, nick) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{email.email}</p>
<strong>Nick: </strong>
<p>{email.phone}</p>
<strong>Phone: </strong>
<p>{email.nick}</p>
</div>
)
}
It works... Someone knows what it can be?
You are passing the props in a wrong way. Either use it as a single object in props or have all the props it inside {} using destructuring method.
export default function List({email, phone, nick}) {}
OR
export default function List(props) {
return (
<div align="center">
<hr />
<strong>Email: </strong>
<p>{props.email}</p>
<strong>Nick: </strong>
<p>{props.phone}</p>
<strong>Phone: </strong>
<p>{props.nick}</p>
</div>
)
}

Why can React display an object but not its members?

I'm trying to wrap my head around the MERN stack. So far I've managed to query my database and get the data on an API endopoint, but I'm having some trouble getting it to show up on my front-end.
Here's my fronted code :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component<{}, {res:any}> {
constructor(props:any) {
super(props);
this.state = {res: Array};
}
callAPI() {
fetch("http://localhost:5000")
.then(res => res.json())
.then(json => this.setState({res: json}));
}
componentWillMount() {
this.callAPI();
}
render() {
// WORKS
console.log(this.state.res[0]);
// DOESN'T WORK
console.log(this.state.res[0].name);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
)};
}
export default App;
As you can see it's just a modified version of the default React homepage. I just added a state and fetching data from my backend.
The problem comes when I try to console.log my data.
If I console.log(this.state.res[0]), everything is fine, and I get { "_id": "62207b47d40bca8ea8b60560", "name": "Patère", "checked": false, "links": [ "" ] } in my console. But if I try to only log the name, I get Uncaught TypeError: this.state.res[0] is undefined, which is weird, since it managed to display this.state.res[0] just fine before ?
What's causing this and how can I fix it ?
Thank you in advance.

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')
);

Resources