Conditional rendering is not working in react - node.js

After getting data from the backend, I can't get to display is on the homepage
Everthing is okay like server, database but conditional rendering is not working
Homepage UI with error
`
import React, {useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getAllPizzas } from "../actions/pizzaActions";
import Error from "../components/Error";
import Loading from "../components/Loading";
import Pizza from "../components/Pizza";
const Homescreen = () => {
const dispatch = useDispatch();
const pizzasstate = useSelector((state) => state.getAllPizzasReducer);
const { pizzas, error, loading } = pizzasstate;
useEffect(() => {
dispatch(getAllPizzas());
}, [dispatch]);
return (
<div>
<div className="row">
{loading ? (
<Loading/>
) : error ? (
<Error error='Something went wrong'/>
) : (
pizzas.map((pizza) => {
return (
<div className="col-md-3 m-3" key={pizza._id}>
<div>
<Pizza pizza={pizza} />
</div>
</div>
);
})
)}
</div>
</div>
);
};
export default Homescreen;
Thank you in advance

Related

Trouble with dividing an API into multiple components instead of just one

I'm having trouble for the past few days in this problem.
Explanation of the problem:
I'm using Axios in order to get data inside of state (Pokémon's), But, everything is rendering inside one component (creating an array and list and shows the list) , while I need every Pokémon I get from the API to be inside his own component (so that I can images per Pokémon and etc.)
Does anybody perhaps knows how to do so? If u do, please answer and explain to me (And if it wont be any trouble, modify the code), Thanks in advance, Mikey. (Using react-ts, node.js and axios)
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function PokeCont() {
const [pokemons, setPokemons] = useState<any>();
const onClick = () => {
axios.get('https://pokeapi.co/api/v2/pokemon?limit=6').then((response) => {
setPokemons(response.data.results);
});
};
useEffect(() => {
onClick();
}, []);
return (
<div>
{pokemons &&
pokemons.map((pokemon: any) => (
<div key={pokemon.name}>
<p>{pokemon.name}</p>
</div>
))}
</div>
);
}
Here is an example ;)
import { useState, useEffect } from "react";
import axios from "axios";
export default function App() {
return (
<div className="App">
<PokemonContainer />
</div>
);
}
function PokemonContainer() {
const [pokemons, setPokemons] = useState<any[]>([]);
const onClick = () => {
axios.get("https://pokeapi.co/api/v2/pokemon?limit=6").then((response) => {
setPokemons(response.data.results);
});
};
useEffect(() => {
onClick();
}, []);
return (
<div>
{pokemons &&
pokemons.map((pokemon) => (
<PokemonItem key={pokemon.name} info={pokemon} />
))}
</div>
);
}
function PokemonItem({ info }) {
return (
<div>
<h2>{info.name}</h2>
<img src={info.image} width="100" height="100" alt=""></img>
</div>
);
}
Add necessary changes to components like export default and types.
import React, { useState, useEffect } from 'react'
import axios from 'axios'
***Component 1: Pokemon***
Pokemon = props => {
return (
<>
<div key={props.name}>
<p>{props.name}</p>
</div>
</>
)
}
***Component 2: Parent Pokemon which renders your Pokemon as Component ***
export default function PokeClass() {
const [pokemons, setPokemons] = useState()
const onClick = () => {
axios.get("https://pokeapi.co/api/v2/pokemon?limit=6").then((response) => {
setPokemons(response.data.results)
})
}
useEffect(() => {
onClick()
}, []);
return (
<>
{pokemons.map((item => {
return <Pokemon name={item.name} />
}))}
</>
)
}

socket.io broadcasting not working with React

I am currently trying to build a connection between a Node.js application in the backend and a React application in the frontend. The connection from the frontend to the backend seems to work without any problems. Unfortunately, the React application, on the other side, cannot accept any data.
The socket.on(...) function throws an error:
dashboard.js:20 Uncaught TypeError: Cannot read properties of null (reading 'on')
I can not explain where the error lies.
app.js (mounting point of the React app):
import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import io from 'socket.io-client';
import Dashboard from "./compontents/views/dashboard/dashboard";
function App() {
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = io(`http://${window.location.hostname}:8040`);
setSocket(newSocket);
return () => newSocket.close();
}, [setSocket]);
return (
<Router>
<div className="app">
<div className="app__view">
<Switch>
<Route exact path="/">
<Dashboard socket={socket} />
</Route>
</Switch>
</div>
</div>
</Router>
);
}
export default App;
dashboard.js (child component):
import React, { useEffect, useState } from 'react';
import { Link } from "react-router-dom";
import FeatherIcon from 'feather-icons-react';
import LargeButton from "../../buttons/largeButton/largeButton";
function Dashboard({ socket }) {
function toggleLight(type) {
if(type) {
// this function works fine
socket.emit("toggle light", type);
console.log(type);
}
}
useEffect(() => {
// this line is causing the error
socket.on('toggle button', (type) => {
console.log(type);
});
}, [socket]);
return(
<div className="view">
<div className="all">
<LargeButton icon="sun" text="Alles einschalten" event={toggleLight} />
<LargeButton icon="moon" text="Alles ausschalten" event={toggleLight} />
</div>
</div>
)
}
export default Dashboard;
It seems like your <Dashboard/> component are mounting before the socket instance are ready to go. Socket connection is an a async procedure so you must take this on mind when you use it.
Try change your app.js to this:
import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import io from 'socket.io-client';
import Dashboard from './compontents/views/dashboard/dashboard';
function App() {
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = io(`http://${window.location.hostname}:8040`);
setSocket(newSocket);
return () => newSocket.close();
}, [setSocket]);
if (!socket) {
// catch and show some loading screen
// while the socket connection gets ready
return <div>Loading...</div>;
}
return (
<Router>
<div className="app">
<div className="app__view">
<Switch>
<Route exact path="/">
<Dashboard socket={socket} />
</Route>
</Switch>
</div>
</div>
</Router>
);
}

useState data not working with .map function

I have this app that fetches the blog posts from an API. The API response with blog posts and I'm getting those blog posts to GetBlogState state. When I'm looping through GetBlogState using the .map I am getting the following error.
The following is the code that I'm currently working with.
import React, { useState, useEffect } from 'react';
import Head from 'next/head'
import axios from 'axios'
import HeaderComponent from '../components/HeaderComponent';
export default function Blog(){
const [GetBlogState, SetBlogState] = useState([]);
useEffect(() => {
axios.get('http://localhost:4000/blog').then(res => {
SetBlogState(res)
}).catch(errr => {
console.log(err)
})
}, []);
return (
<div className="MyApp">
{ GetBlogState.map(item => (
<div className="h-68">
<img className="w-full" alt="post" src='post.jpg' />
<div className="mt-3 mb-2 text-xs">May 10, 2018</div>
<h2 className="font-bold mb-5 text-xl">{ item.Title } </h2>
<p>{item.content}</p>
</div>
))}
</div>
)
}
I think you should check the output what you are getting in res from axios.
you are setting response object in state which is wrong.
You should do
useEffect(() => {
axios.get('http://localhost:4000/blog').then(res => {
//// console.log(res) Check whats returning in res \\\
SetBlogState(res.data)
}).catch(errr => {
console.log(err)
})
}, []);
Axios' response schema put server response in data. Hence set state like SetBlogState(res.data)

Failed to compile ./src/App.js Line 30:3: 'onInputChange' is not defined no-undef

Failed to compile
./src/App.js
Line 30:3: 'onInputChange' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
The code of App.js
import React from 'react';
import Logo from './components/Logo/Logo';
import './App.css';
import Navigation from './components/Navigation/Navigation';
import ImageLinkForm from './components/imagelink/ImageLinkForm';
import Rank from './components/Rank/rank'
import Particles from 'react-particles-js';
const particlesOptions= {
particles: {
number:{
value:30,
density:{
enable:true,
value_area:800
}
}
}
}
function App() {
constructor()
{
super();
this.state = {
input: '',
}
}
onInputChange = (event) => {
console.log(event.target.value);
}
return (
<div className="App">
<Particles className="particles"
params={particlesOptions} />
<Navigation/>
<Logo/>
<Rank/>
<ImageLinkForm onInputChange={this.onInputChange}/>
{/*<FaceRecognition/>*/}
</div>
);
}
export default App;
The code of ImageLinkForm.js
import React from 'react';
import './ImageLinkForm.css';
const ImageLinkForm = ({ onInputChange }) => {
return (
<div>
<p className='f3'>
{'This Magic Brain will detect faces in your pictures'}
</p>
<div className='center'>
<div className='form center pa4 br3 shadow-5'>
<input className='f4 pa2 w-70 center' type='tex' onChange={onInputChange}/>
<button className='w-30 grow f4 link pv2 dib white bg-light-purple'>Detect</button>
</div>
</div>
</div>
);
}
export default ImageLinkForm;
I want to know how to fix this error.
I solved it.
By writing a class on it.
App.js
import React, { Component } from 'react';
import Logo from './components/Logo/Logo';
import './App.css';
import Navigation from './components/Navigation/Navigation';
import ImageLinkForm from './components/imagelink/ImageLinkForm';
import Rank from './components/Rank/rank'
import Particles from 'react-particles-js';
const particlesOptions= {
particles: {
number:{
value:30,
density:{
enable:true,
value_area:800
}
}
}
}
class App extends Component
{
constructor()
{
super();
this.state = {
input: '',
}
}
onInputChange = (event) => {
console.log(event.target.value);
}
render(){
return (
<div className="App">
<Particles className="particles"
params={particlesOptions} />
<Navigation/>
<Logo/>
<Rank/>
<ImageLinkForm onInputChange={this.onInputChange}/>
{/*<FaceRecognition/>*/}
</div>
);
}
}
export default App;

pass state as props in component child in React

I get data from a local server, catch them with axios.get, and save them in my state. It's ok, but when i want to pass it as props in an component child, KABOOM! Doesn't work.
I'm looking for a solution, I think it's lyfecycle problem but i'm not sure.
App.js
import React, { Component } from 'react';
import './style/App.css';
import axios from 'axios'
import Table from './Components/Table'
class App extends Component {
state = {
tabData: [],
}
componentWillMount = () => {
this.getDataFromServer()
}
getDataFromServer = () => {
axios.get("http://localhost:8000")
.then((response) => {
const twentyObj = response.data.splice(-20);
this.setState({
tabData:twentyObj
})
console.log(this.state.tabData)
})
.catch(function (error) {
console.log(error);
})
}
render() {
return (
<div className="App">
<Table stateData={this.state.tabData}/>
</div>
);
}
}
export default App;
Developer Tools Browser say:
TypeError: _this.props is undefined
(for this.props.tabData.map in Table.js)
Table.js
import React from 'react';
import Cell from './Cell'
const Table = (props) => {
return(
<div>
{this.props.tabData.map( item =>
<Cell key={item.index}
time={item.timestamp}
nasdaq={item.stocks.NASDAQ}
cac40={item.stocks.CAC40}/>
)}
</div>
)
}
export default Table;
Table is functional component this has no value there and thats what the error message is telling you.
You should use props.tabData and not this.props.tabData
UPDATE:
Here you are passing it as stateData and not tabData Try props.stateData

Resources