Using axios post response in the jsx react - node.js

I want to take the data response from the Axios post, and display it on the page:
import React, { useRef} from 'react';
import logo from './assets/img/lupa.png';
import { Form } from "#unform/web";
import Input from './components/forms/input';
import * as Yup from "yup";
import './App.css';
import axios from 'axios';
function App() {
const formRef = useRef(null);
async function handleSubmit(data, ){
try{
const schema = Yup.object().shape({
nn: Yup.number().min(8,"O campo eh obrigatorio e precisa ter 8 ou mais caracteres")
})
await schema.validate(data)
console.log(data)
}catch(err){
if(err instanceof Yup.ValidationError){
console.log(err)
}}
axios.post("http://localhost:8080/api", data).then(res => console.log(res.data))
.catch(err => console.log(err));
}
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>$ Search $</h2>
</div>
<Form ref={formRef} onSubmit={handleSubmit}>
<Input name="nn" type="number"/>
<button type='submit'>buscar</button>
</Form>
</div>
);
}
export default App;
But I don't know how to work with that res.data and how to display it on the page by the jsx react, I tried to use useState and set it in the axios.post("http://localhost:8080/api", data).then(res => setState(res.data))
.catch(err => console.log(err)); - but when I console.log someState it brings an object null, i tried to display on the page using
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>$ Search $</h2>
</div>
<Form ref={formRef} onSubmit={handleSubmit}>
<Input name="nn" type="number"/>
<button type='submit'>buscar</button>
</Form>
{
someState.length >=1 ? someState.map((some, idx) =>{
return <p key={idx}>{some.data}</p>
})
: ""
}
</div>
);
}
but nothing were display! ( If you have some suggestion to change of the overall code, you can answer too ), How can I fix this 2 problems ? I want to learn moreThe first object Im printing my input, to check if it are working, and the second object its what I recieved from the axios post response(.then(res => console.log(res.data), I want to display this object "resultado"
Object { nn: "00000000353" }
Object { ip: "200.1******", resultado: 961 }
​
ip: "200.1*****"
​
resultado: 961
​
<prototype>: Object { … }

See this nice post by digitalOcean How to use axios in ReactJs
https://www.digitalocean.com/community/tutorials/react-axios-react
Hope you got a lot of help from this post.

Related

After adding router in App.js in react nothing is displayed in the webpage

After using the BrowserRouter as a wrapper function nothing is displayed on the webpage.
App.js
import React, { Component } from 'react';
import './App.css';
import Homepage from './components/homepage/homepage';
import Login from './components/login/login';
import Register from './components/register/register';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
// <div className="App">
<Router>
<div className="App">
<ul >
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/register">Register</Link>
</li>
</ul>
<Routes>
<Route exact path='/' element={< Homepage />}></Route>
<Route exact path='/login' element={< Login />}></Route>
<Route exact path='/register' element={< Register />}></Route>
</Routes>
</div>
</Router>
// </div>
);
}
export default App;
homepage.js
import React from "react"
import "./homepg.css"
const Homepage = () => {
return (
<div className="homepage">
<h1>Hello Homepage</h1>
<div className="button">Logout</div>
</div>
)
}
export default Homepage
login.js
import React, {useState} from "react"
import "./login.css"
import axios from "axios"
const Login = () => {
const [ user, setUser ] = useState({
email : "",
password : ""
})
const handleChange = e => {
const {name , value} = e.target
setUser({
...user,
[name] : value
})
}
const login = () => {
axios.post("http://localhost:9002/login",user)
.then(res => alert(res.data.message))
}
return (
<div className="login">
{console.log("User",user)}
<h1>Login</h1>
<input type="text" name="email" value={user.email} placeholder="Enter email" onChange={handleChange}></input>
<input type="password" name="password" value={user.password} placeholder="Enter password" onChange={handleChange}></input>
<div className="button" onClick={login}>Login</div>
<div>or</div>
<div className="button">Register</div>
</div>
)
}
export default Login
register.js
import React, {useState} from "react"
import "./register.css"
import axios from "axios"
const Register = () => {
const [ user, setUser ] = useState({
name: "",
email : "",
password : "",
reEnterPassword : ""
})
const handleChange = e => {
const {name , value} = e.target
setUser({
...user,
[name] : value
})
}
const register = () =>{
const {name,email,password, reEnterPassword} = user
if(name && email && password && (password === reEnterPassword)){
axios.post("http://localhost:9002/register", user)
// console.log("yo")
.then(res => console.log(res))
}
else{
alert("Invalid input")
}
}
return (
<div className="register">
{console.log("User",user)}
<h1>Register</h1>
<input type="text" name="name" value={user.name} placeholder="Your Name" onChange={handleChange}></input>
<input type="text" name="email" value={user.email} placeholder="Your Email" onChange={handleChange}></input>
<input type="password" name="password" value={user.password} placeholder="Your password" onChange={handleChange}></input>
<input type="password" name="reEnterPassword" value={user.reEnterPassword} placeholder="Re-enter password" onChange={handleChange}></input>
<div className="button" onClick={register}>Register</div>
<div>or</div>
<div className="button">Login</div>
</div>
)
}
export default Register
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />,
);
If only <Homepage />, <Login/>, and <Register /> are present then homepage, login, and register page gets displayed.
But once I use the Router from react-router-dom then the webpage is blank, nothing is displayed.
There are several reasons why your components are not being displayed when using the BrowserRouter component from the react-router-dom library. Some of the most common reasons include:
1. Incorrect Router Import: Make sure you have imported the BrowserRouter component correctly from the react-router-dom library. The correct import statement is: import { BrowserRouter } from 'react-router-dom'.
2. Wrapping the Wrong Components: Make sure that you are wrapping the correct components inside the BrowserRouter. The BrowserRouter should wrap all the components that need access to the routing functionality.
3. Incorrect Route Configuration: Make sure you have correctly set up your routes using the Route component. The Route component should be used to define the mapping between a path and a component.
4. Components not Exporting Correctly: Make sure that your components are being exported correctly. Each component should be exported using export default ComponentName.
If you provide more information about your code and the error message that you're encountering, I'd be happy to help you further.

App.js:32 Uncaught TypeError: Tasks.map is not a function

I really don't know what's actually wrong with the code(below)
import Todo from './components/task.js'
import axios from 'axios'
import { useState } from 'react';
import { useEffect } from 'react';
function App() {
const [Tasks, setTasks] = useState([]);
useEffect(() => {
async function fetchTasks() {
await axios.get('http://localhost:5000/task')
.then(({data})=> setTasks(data))
.catch((err)=>console.log(err))
}
fetchTasks();
}, []);
if (Error){
<p>{Error.message}</p>
}
return (
<div className="App">
<div className="container-container">
<h1>AppTodo</h1>
<div className="input-class">
<input type="text" placeholder="Add your todos" id="input1-id" />
<input type="submit" id="input2-id" value="Add" />
</div>
{Tasks.map((items) => <Todo key={items._id} text={items.name} />)}
</div>
</div>
);
}
export default App;
I tried changing to fetch api method and yet still can't get anything also tried to console.log the Tasks hence I have setTask in the useEffect() it seems the it fail to set it inside the task. I am just expecting the output of the list of the items.
Add Optional chaining operator with the Task array like below
{Tasks?.map((items) => )}
You just need to reomve {} curly brackets from data in .then
useEffect(() => {
async function fetchTasks() {
await axios.get('http://localhost:5000/task')
.then((data)=> setTasks(data))
.catch((err)=>console.log(err))
}
fetchTasks();
}, []);
I have removed your curly brackets from line 5.

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)

Pass a valid time type usnig moment from React setState to postgres

I am new in coding and essentially in React. I am trying to create a human resource management system that will have an employee and an admin. I am now working on using an axios to post to knex postgres as db and nodejs.
I need help to pass in a correct value with format of "HH:mm:ss" to my backend taking time type.
This is my knex migration:
exports.up = function(knex) {
return knex.schema.createTable('undertime_overtime', (table) => {
table.increments('id').primary();
table.date('date_filed').notNullable(); //has to be default date now?
table.time('from_time').notNullable();
table.time('to_time').notNullable();
table.string('reason').notNullable();
table.integer('time_type').defaultTo(1);
table.boolean('isDeleted').defaultTo(0);
table.boolean('isAccepted').defaultTo(0);
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('modified_at').defaultTo(null);
table.integer('created_by').unsigned().notNullable();
table.foreign('created_by').references('employees.id');
});
Here are the things I tried that did not work:
state = {
date_filed: new Date(),
from_time: moment().format("HH:mm:ss").toString(),
to_time: moment().format("HH:mm:ss"),
reason: '',
time_type: 1,
created_by: 1 //todo
};
handleFromTime = time => {
this.setState({
from_time: time.format("HH:mm:ss")
});
console.log(time("HH:mm:ss"));
};
Here is my component:
import React, { Component } from 'react';
import moment from 'moment';
import { Content, Row, Col, Box, Button } from 'adminlte-2-react';
import TimePicker from 'rc-time-picker';
import DatePicker from "react-datepicker";
import axios from 'axios'
import 'rc-time-picker/assets/index.css';
class OvertimeComponent extends Component {
state = {
date_filed: new Date(),
from_time: moment(),
to_time: moment(),
reason: '',
time_type: 1,
created_by: 1 //todo
};
handleChangeDateFiled = date => {
this.setState({
date_filed: date
});
console.log(date)
};
handleFromTime = time => {
this.setState({
from_time: time
});
console.log(time);
};
handleToTime = time => {
this.setState({
to_time: time
});
console.log(time.format('HH:mm:ss'));
};
handleReason = event => {
this.setState({
reason: event.target.value
})
console.log(event.target.value);
}
handleSubmit = event => {
console.log(`date-> ${this.state.date_filed} from ${this.state.from_time} to ${this.state.to_time} reason ${this.state.reason}`)
event.preventDefault()
axios.post('http://localhost:8080/api/time',this.state)
.then(response=> {
console.log(response);
}).catch(error => {
console.error(error);
})
}
footer = [
<Button key="btnSubmit" type="success" pullRight text="Submit" onClick={this.handleSubmit} />,
];
render() {
return (
<Content title="Overtime" subTitle="Requests" browserTitle="Overtime">
<Row>
<Col md={6}>
<Row>
<Col xs={12}>
<Box title="Overtime Application" type="primary" collapsable footer={this.footer}>
<div className="form-group">
<label>Date</label>
<div>
<DatePicker name="date_filed" selected={this.state.date_filed} onChange={this.handleChangeDateFiled}/>
</div>
</div>
<div className="form-group">
<label>From</label>
<div>
<TimePicker name="from_time" value={this.state.from_time} onChange={this.handleFromTime} />
</div>
</div>
<div className="form-group">
<label>To</label>
<div>
<TimePicker name="to_time" value={this.state.to_time} onChange={this.handleToTime} />
</div>
</div>
<div className="form-group">
<label>Reason</label>
<textarea type="text" name="reason" value={this.state.reason} onChange={this.handleReason} className="form-control" placeholder="Enter ..." />
</div>
</Box>
</Col>
</Row>
</Col>
<Col md={6}>
<Box title="Request Status" type="primary" collapsable>
<div className="form-group">
<label>todo</label>
</div>
</Box>
</Col>
</Row>
</Content>);
}
}
export default OvertimeComponent;
I found the issue. I should've touched the axios post to get the format I wanted from the moment object.
axios.post('http://localhost:8080/api/time',{
'date_filed':this.state.date_filed,
'from_time':this.state.from_time.format('HH:mm:ss'),
'to_time':this.state.to_time.format('HH:mm:ss'),
'reason':this.state.reason,
'created_by': 1 //todo
})

Missing "key" prop for element. (ReactJS and TypeScript)

I am using below code for reactJS and typescript. While executing the commands I get below error.
I also added the import statement
import 'bootstrap/dist/css/bootstrap.min.css';
in Index.tsx.
Is there a way to fix this issue?
npm start
client/src/Results.tsx
(32,21): Missing "key" prop for element.
The file is as below "Results.tsx"
import * as React from 'react';
class Results extends React.Component<{}, any> {
constructor(props: any) {
super(props);
this.state = {
topics: [],
isLoading: false
};
}
componentDidMount() {
this.setState({isLoading: true});
fetch('http://localhost:8080/topics')
.then(response => response.json())
.then(data => this.setState({topics: data, isLoading: false}));
}
render() {
const {topics, isLoading} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<h2>Results List</h2>
{topics.map((topic: any) =>
<div className="panel panel-default">
<div className="panel-heading" key={topic.id}>{topic.name}</div>
<div className="panel-body" key={topic.id}>{topic.description}</div>
</div>
)}
</div>
);
}
}
export default Results;
You are rendering an array of elements, so React needs a key prop (see react docs) to identify elements and optimize things.
Add key={topic.id} to your jsx:
return (
<div>
<h2>Results List</h2>
{topics.map((topic: any) =>
<div className="panel panel-default" key={topic.id}>
<div className="panel-heading">{topic.name}</div>
<div className="panel-body">{topic.description}</div>
</div>
)}
</div>
);
This has helped me
React special props should not be accessed
https://deepscan.io/docs/rules/react-bad-special-props

Resources