How to get data [closed] - reactjs

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am working on react project, In my project I am trying to get data from backend my Api is also working fine by I am unable to display data in front end in table format. So please help me to display data in table format.
This is my code
import React, { Component } from 'react';
import './Profiles.css';
import axios from 'axios';
export default class Profiles extends Component {
constructor(props) {
super(props)
this.state = {
products: []
}
}
async getProfiles() {
try {
const res = await axios.get('http://localhost:5000/api/products');
this.setState( { products: res.data } )
} catch (error) {
console.log(error)
}
}
render() {
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<table className="table table-bordered">
<thead>
<tr>
<th>Brand</th>
<th>Price</th>
<th>Replacement</th>
<th>Discount</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.jobs.map(currentValue =>
<tr>
<td>{currentValue.name}</td>
<td>{currentValue.position}</td>
<td>{currentValue.location}</td>
<td>{currentValue.salary}</td>
<td>
<button className='btn btn-primary'>Edit</button>
</td>
<td>
<button className='btn btn-danger'>Delete</button>
</td>
</tr>
)}
</tbody>
</table>

import React, { Component } from 'react';
import './Profiles.css';
import axios from 'axios';
export default class Profiles extends Component {
constructor(props) {
super(props)
this.state = {
jobs: []
}
}
componentDidMount() {
this.getProfiles()
}
async getProfiles() {
try {
const res = await axios.get('http://localhost:7500/api/registration');
this.setState( { jobs: res.data } )
} catch (error) {
console.log(error)
}
}
render() {
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<table className="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Location</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.jobs.map(currentValue =>
<tr>
<td>{currentValue.name}</td>
<td>{currentValue.position}</td>
<td>{currentValue.location}</td>
<td>{currentValue.salary}</td>
<td>
<button className='btn btn-primary'>Edit</button>
</td>
<td>
<button className='btn btn-danger'>Delete</button>
</td>
</tr>
)}
</tbody>
</table>

Related

React not fetching data anymore

Hi there I'm fairly new to react and I'm trying to create a student management app with React as a frontend and i can't seem to get the page to return a list of students since I tried working with the functions useHistory and useNavigate from react-router-dom to try redirect to an individual student component but I was unable to get them working on my project so I removed them.
The page was rendering the student objects from the backend API i created just fine before I tried implementing the two functions but now won't render any student object, all that is displayed are the table heads but not the table rows any help on what the problem would be appreciated
here is my hook component to fetch data before using useHistory & useNavigate
function GetAllStudents() {
const [students, setStudents] = useState([]);
const fetchData = async () => {
StudentService.getStudents() //axios service function used to fetch data
.then((res) => res.json())
.then((res) => {
const currentStudent = res.data;
setStudents(currentStudent); // try setStudents(res.data) if fails
})
.catch((err) => {
console.log(err);
});
// fetchData();
};
useEffect(() => fetchData(), []);
return (
<div class="container">
<div class="form container p-4">
<h1>Week 10 - React Frontend </h1>
<a href="/add" class="btn btn-success">
Add Student
</a>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{students.map((student) => (
<tr key={student.id}>
<td> {student.firstname} </td>
<td> {student.lastname}</td>
<td> {student.email}</td>
<td>
<button className="btn btn-info">Edit</button>
<button
style={{ marginLeft: '10px' }}
className="btn btn-danger"
onclick="return confirm('Do you Really want to delete')">
Delete{' '}
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default GetAllStudents;
When I inspect elements on my browser it shows the state is not saving the objects to the array
I don't know what I misconfigured because even when I change the function to a class component that also previously worked properly doesn't display the objects anymore
import React, { Component } from 'react';
import StudentService from '../services/StudentService';
class GetAllStudents extends Component {
constructor(props) {
super(props);
this.state = {
students: [],
};
this.addStudent = this.addStudent.bind(this);
this.editStudent = this.editStudent.bind(this);
this.deleteStudent = this.deleteStudent.bind(this);
}
deleteStudent(id) {
StudentService.deleteStudent(id).then((res) => {
this.setState({
students: this.state.students.filter((student) => student.id !== id),
});
});
}
updateStudent(id) {
this.props.history.push(`/students/${id}`); // props(parameter) to navigate to edit student component
}
editStudent(id) {
this.props.history.push(`/edit/${id}`); // props(parameter) to navigate to edit student component
}
componentDidMount() {
StudentService.getStudents().then((res) => {
this.setState({ students: res.data }); //loads all students in database
});
}
addStudent() {
this.props.history.push('/add'); //function to navigate to edit student component with form to add student
}
render() {
return (
<div class="container">
<div class="form container p-4">
<h1>Week 10 - React Frontend </h1>
<a href="/add" class="btn btn-success">
Add Student
</a>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.state.students.map((student) => (
<tr key={student.id}>
<td> {student.firstname} </td>
<td> {student.lastname}</td>
<td> {student.email}</td>
<td>
<button
onClick={() => this.updateStudent(student.id)}
className="btn btn-info">
Edit
</button>
<button
style={{ marginLeft: '10px' }}
onClick={() => this.deleteStudent(student.id)}
className="btn btn-danger"
onclick="return confirm('Do you Really want to delete')">
Delete{' '}
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default GetAllStudents;
when I check my backend it shows calls are being made to the server but react isn't fetching or displaying data
any help on how to solve this problem would be appreciated as I currently don't know what I did wrong

Am I using API in react correctly? I am not getting any output

import React,{useState,useEffect} from 'react';
import "../Track.css";
const Tracker = () => {
const[data,setData]= useState([]);
const getCovidData = async() =>{
const res = await fetch('https://api.rootnet.in/covid19-in/stats/latest');
const actualData = await res.json();
console.log(actualData.regional);
setData(actualData.regional);
}
useEffect(() => {
getCovidData();
}, []);
return (
<>
<div className="conatiner-fluid mt-5">
<div className="main-heading">
<h1 className="mb-5 text-center"> <span className="font-weight-bold">INDIA</span> COVID-19 DASHBOARD</h1>
</div>
<div className="table-responsive">
<table className="table table-hover">
<thead className="thead-dark">
<tr>
<th> STATE</th>
<th> CONFIRMED</th>
<th> RECOVERED</th>
<th> DEATHS</th>
<th> ACTIVE</th>
<th> UPDATED</th>
</tr>
</thead>
<tbody>
{
data && data.map((curElem,ind,regional) => {
return(
<tr key={ind}>
<th> {curElem?.loc} </th>
<td> {curElem?.confirmedCasesIndian} </td>
<td> {curElem?.discharged} </td>
<td> {curElem?.deaths} </td>
<td> {curElem?.lastOriginUpdate} </td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
</>
)
}
export default Tracker
I am not getting output of api values in the output page. Pls help as their may be the mistake in map function. pls share your views and and share solution if possible.
regional is inside data object.
{
"success": true,
"data": {
"summary": {...}
"unofficial-summary" : [...],
"regional" : [...]
...
}
}
You need to change setData(actualData.regional); as below
// ...
const getCovidData = async() =>{
const res = await fetch('https://api.rootnet.in/covid19-in/stats/latest');
const actualData = await res.json();
console.log(actualData.regional);
setData(actualData.data.regional);
}

Getting this warning "Functions are not valid as a React child"

I am trying to render a list of movies from an array object in an html table format. I am getting this warning:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
import React from 'react';
import {movies} from '../services/fakeMovieService';
class Movies extends React.Component {
constructor(props) {
super(props);
this.tableFormat = this.tableFormat.bind(this);
}
tableFormat() {
movies.map((movie) => {
return (
<tr>
<td key={movie._id}>{movie.title}</td>
</tr>
);
});
}
render() {
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
</tr>
</thead>
<tbody>
{this.tableFormat()}
</tbody>
</table>
);
}
}
export default Movies;
You forgot to call your function.
<tbody>
{this.tableformatter()}
</tbody>
But even by doing, I don't think the result is going to be what you expect.
To render an array of elements in React you should use the map function as said in the docs.
The following result would be :
<tbody>
{movies.map(movie =>
<tr key={movie.title}>
<td>{movie.title}</td>
</tr>
)}
</tbody>
EDIT:
I made a typo and put movies instead of movie.
The following code should do everything you are looking for using map and inline conditions:
const movies = [
{
title: "Spooky",
genre: 'eziojgf',
stock: 'nope',
rate: 87
},
{
title: "Sharknado",
genre: 'shitty',
stock: 'yes',
},
{
title: "haha yes"
},
{
title: "uhmmmm",
rate: -5
}
]
class Movies extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
</tr>
</thead>
<tbody>
{movies.map(movie =>
<tr key={movie.title}>
{['title', 'genre', 'stock', 'rate'].map(category => <td key={category}>{movie[category]}</td>)}
</tr>
)}
</tbody>
</table>
);
}
}
ReactDOM.render(<Movies />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
<div id='root'>
Please execute function as following:
<tbody>
{this.tableformatter()}
</tbody>
here is the right way how to resolve this with React
function TableFormatter ({title /* , and other props genre, rate etc. *//}) {
return (
<tr>
<td>{title}</td>
{/* you may want to add other td here *//}
</tr>
)
}
function Table({movies}) {
render() {
return (
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Stock</th>
<th>Rate</th>
</tr>
</thead>
<tbody>
{movies.map(movie => <TableFormatter key={movie.id} {...movie} />)}
</tbody>
</table>
);
}
}

Elements not rendering in react

I am doing a fetch and storing the result in my state "data", then i am sending this "data" to the function "Showingmovies" , there i am using table tag to align my layout . But the elements are not being rendered from the "Showingmovies" function, i have found that the props are being succesfully passed to the function still it is not rendering.
Below is my complete code -
import React, { Component } from 'react'
function Showingmovies(props){
console.log("in showingmovies",props.mov)
return(
<table>
<tbody>
{props.mov.results.map((mv) =>{
<tr>
<td>
<p>image here</p>
</td>
<td>
{mv.original_title}
<p>{mv.overview}</p>
</td>
</tr>
})}
</tbody>
</table>
)}
export default class movie extends Component {
constructor(){
super()
this.state={
data: [],
}
}
componentWillMount(){
fetch("https://api.themoviedb.org/3/search/movie?
api_key=ab85c167dc8f5538f5b6e08f01923243&query=J")
.then((res) =>res.json())
.then((data) => this.setState({
data: data,
}))
}
render() {
return (
<div>
<p>hi i will show you movies</p>
{this.state.data.length !== 0 ?
<Showingmovies mov = {this.state.data}/>:null}
</div>
)
}
}
You need to add return in the map method as
function Showingmovies(props){
return(
<table>
<tbody>
{props.mov.results.map((mv) =>{
return (
<tr>
<td>
<p>image here</p>
</td>
<td>
{mv.original_title}
<p>{mv.overview}</p>
</td>
</tr>
)
})}
</tbody>
</table>
)}
Problem is return
Solution
Whenever you use map you must use return if you use `{} like
{props.mov.results &&
props.mov.results.map(mv => {
return <tr>
<td>
<p>image here</p>
</td>
<td>
{mv.original_title}
<p>{mv.overview}</p>
</td>
</tr>;
})}
and if you are not don't want to return then remove {} like
{props.mov.results && props.mov.results.map(mv =>
<tr>
<td>
<p>image here</p>
</td>
<td>
{mv.original_title}
<p>{mv.overview}</p>
</td>
</tr>)
}
codeSandbox

Display search results on keypress

I am tryng to display search results for each key press on my input:
getMovies(e){
axios.get(`http://www.omdbapi.com/?t=${e.target.value}`)
.then((response) => {
this.setState({ movies: response.data });
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<div className="container">
<SearchForm onkeydown={this.getMovies} />
<MovieList movies={this.state.movies}/>
</div>
);
}
}
In my search form I bind my function to the FormControl onChange:
export default class SearchForm extends React.Component{
render(){
return(
<Row>
<Col md={6} >
<h2>Custom search field</h2>
<div className="custom-search-input">
<Col md={12} className="input-group" >
<FormControl
type="text"
bsSize="lg"
value={this.props.val}
placeholder="Enter text"
onChange={this.props.onkeydown.bind(this)}
/>
<span className="input-group-btn">
<button className="btn btn-lg" type="button">
<i className="glyphicon glyphicon-search"></i>
</button>
</span>
</Col>
</div>
</Col>
</Row>)
}
}
My movielist component:
export default class MovieList extends React.Component{
render(){
var userNodes = this.props.movies.map(function(movie){
return (
<tr key={movie.id}>
<td>{movie.Year}</td>
<td >{movie.Title}</td>
<td >{movie.Released}</td>
</tr>
)
});
return (
<div>
<Table responsive>
<thead>
<tr>
<th>id</th>
<th>Year</th>
<th>Title</th>
<th>Released</th>
</tr>
</thead>
<tbody>
{userNodes}
</tbody>
</Table>
</div>
);
}
}
I can get the response on the network panel, but the state is not updating to display the MovieList component.
How can I update the state and display it in my MovieList ?
I've checked that API and seems it returns an object, not an array.
Update 1
You can convert your component in something like:
export default class MovieList extends React.Component{
render(){
const { movie } = this.props;
return (
<div>
<Table responsive>
<thead>
<tr>
<th>Id</th>
<th>Year</th>
<th>Title</th>
<th>Released</th>
</tr>
</thead>
<tbody>
<tr>
<td>{movie.imdbID}</td>
<td>{movie.Year}</td>
<td>{movie.Title}</td>
<td>{movie.Released}</td>
</tr>
</tbody>
</Table>
</div>
);
}
}
and use it like:
<MovieList movie={this.state.movies} />
Please notice I'm using movie instead of movies.
Update 2:
You can also (and I would suggest doing this) convert your MovieList into a dumb functional component:
const MovieList = ({ movie }) => (
<div>
<Table responsive>
<thead>
<tr>
<th>Id</th>
<th>Year</th>
<th>Title</th>
<th>Released</th>
</tr>
</thead>
<tbody>
<tr>
<td>{movie.imdbID}</td>
<td>{movie.Year}</td>
<td>{movie.Title}</td>
<td>{movie.Released}</td>
</tr>
</tbody>
</Table>
</div>
)
export default MovieList;

Resources