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

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.

Related

How to fetch object array from node using Axios

I need to store the data from the response in state. once the axios call has been made and returned some data, the useEffect function will be called and cause the task list array to be populated. The result of which can then be iterated over and displayed on the front end.
import{ useEffect, useState} from 'react'
import axios from 'axios';
function Todo() {
const [toDos,setToDos] =useState([])
function HandleSubmit(e) {
e.preventDefault();
let request ={
list : toDos
}
let taskList = axios.post('http://localhost:8080/Todo',request)
.then(resp=>{
alert(resp.data.message);
})
.catch( err=>{
console.log(err);
})
const [tasks,setTasks] = useState([]);
useEffect(()=>{
setTasks(taskList);
},[taskList]);
}
return (
<div >
<h1>ToDo List</h1>
<form onSubmit={HandleSubmit}>
<input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
{tasks.map(()=>{
return(
<div>
<h1>{tasks}</h1>
</div>
)
})}
<button id="btn" type="submit">Add</button>
</form>
</div>
);
}
export default Todo;
node code
const lists =[
{toDo:"learn react"}
]
app.post('/Todo',function(req, res){
lists.push({ "toDo":req.body.list})
console.log(lists)
res.status(200).send({ message: "Task added!!"})
}
)
Line 23:16: 'tasks' is assigned a value but never used no-unused-vars
ERROR in [eslint]
src\Todoapp\Todo.js
Line 36:10: 'tasks' is not defined no-undef
Line 39:20: 'tasks' is not defined no-undef
Search for the keywords to learn more about each error.
this is error anyone can please help
Define state and in component level and remove useEffect. Don't define state and effect in functional level
function Todo() {
const [tasks,setTasks] = useState([]);
.....
Then set the values inside the then
axios.post('http://localhost:8080/Todo',request)
.then(resp=>{
setTasks(resp.data.message);
})
.catch( err=>{
console.log(err);
})
}

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

Using axios post response in the jsx react

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.

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)

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