NEXT.js Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource - node.js

Hi guys I've created fullstack app with NEXT.js, TypeScript, NODE.js and MongoDB. Generally this is decode\encode app with all functionality on Backend side. My backend side is already deployed on heroku. Front-end I still have on a localhost till I solve this problem. When I fetch all of my data from Backend, first I see error mesage, then data from Backend.
Here below error msg:
And here below my code:
import { ListProps } from "./List.props";
import styles from "./List.module.css";
import { P } from '../'
import React, { useEffect, useState } from "react";
import axios from "axios";
export const List = ({ children, className, ...props }: ListProps): JSX.Element => {
const [blogs, setBlogs] = useState<any[]>([]);
useEffect(() => {
const fetchData = async () => {
await fetch(`https://node-test-mongo.herokuapp.com/api/blog`)
.then((response) => {
return response.json();
})
.then((data) => {
setBlogs(data.blogs)
})
};
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [blogs]);
return (
<div
className={styles.ul}
{...props}
>
{blogs && blogs.map((blog, index) => (
<ul key={blog._id}>
<li className={styles.li}>
<P className={styles.title} size='l'>{blog.title}</P>
<P size='l'>description={blog.text} </P>
</li>
</ul>
))}
</div>
)
};
I suppose, that there could be something wrong with my data fetching, but I'm not sure.
Thank you in advance!:)

Related

Fetch request unable to get backend data due to Uncaught AxiosError - next.js and express.js

I'm trying to fetch some backend data on my Express.js backend which looks like this:
const express = require('express')
const app = express()
app.get("/api", (req, res) => {
res.json({"data": ["data1", "data2", "data3"]})
})
app.listen(5000, () => { console.log("Server started on port 5000, hi") })
Every time the specific page loads I want it to fetch the {"data": ["data1", "data2", "data3"]} from the backend, I added a button that makes the same request for testing as well. Whenever I click the button and whenever the page loads I get this error:
I don't really understand why I'm getting this error, here is my next.js code:
import React, { Component, useEffect, useState } from 'react';
import axios from 'axios';
export default function Product() {
const [backendData, setBackendData] = useState([{}])
useEffect(() => {
axios.get('/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("ran")
}, [])
const test = () => {
axios.get('/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("test clicked")
}
return (
<div style={styles.container}>
<div style={styles.speechTitle}>Talk to us, tell us about your day...</div>
<div style={styles.speechBox}>
Test
</div>
<button onClick={console.log("start")}>
Start
</button>
<button onClick={console.log("stop")}>Stop</button>
<button onClick={console.log("reset")}>Reset</button>
{(typeof backendData.data === 'undefined') ? (
<p>Loading...</p>
) : (
backendData.data.map((data, i) => (
<p key={i}>{data}</p>
))
)}
<button onClick={() => test()}>asdasd</button>
</div>
);
}
I'm running this component called Product you see above in this file called product.js which is in my pages folder:
import React from 'react';
import { ThemeProvider } from 'theme-ui';
import { StickyProvider } from 'contexts/app/app.provider';
import theme from 'theme';
import SEO from 'components/seo';
import Layout from 'components/layout';
import Product from 'components/product-input'
export default function ProductPage() {
return (
<ThemeProvider theme={theme}>
<StickyProvider>
<Layout>
<SEO title="Talkhappi" />
<Product/>
</Layout>
</StickyProvider>
</ThemeProvider>
);
}
I am also getting a network error when I open up the network tab in developer tools:
I'm unsure how to fix this problem and retrieve the data I want to retrieve from my backend running at port 5000.
You seem to have to call your apis at port 5000 instead of 3000 you did.
const baseURL = 'http://localhost:5000';
const test = () => {
axios.get(baseURL + '/api').then(
response => response.json()
).then(
data => {
setBackendData(data)
}
)
console.log("test clicked")
}

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

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)

When i try to call the api data from axios i get 404 error

code for HomeScreen.js to fetch the data:
Setting proxy in package.json
"proxy": "http://127.0.0.1:5000"
I am trying to get the data from the local server as shown in the image below
Error 404 that I get
Image of data to fetch
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import data from '../data';
import axios from 'axios';
function HomeScreen(props) {
const [products, setProduct] = useState([]);
useEffect(() => {
const fetchData = async () => {
const {data} = await axios.get("/api/products");
setProduct(data);
}
fetchData();
return() => {
};
}, [])
return <ul className="products">
{
products.map(product =>
<li key={product._id}>
<div className="product">
<Link to={'/product/' + product._id}><img className="product-image" src="/images/d1.jpg" alt="Product" />
</Link>
<div className="product-name"><Link to={'/product/' + product._id}> {product.name}</Link></div>
<div className="product-brand">{product.brand}</div>
<div className="product-price">{product.price}</div>
<div className="product-rating">{product.rating} Stars {product.numReviews}</div>
</div>
</li>
)
}
</ul>
}
export default HomeScreen;
You're trying to fetch data with relative path /api/products and if you see your error, browser is trying to fetch http://localhost:3000/api/products.
Change your fetch to this:
axios.get("http://localhost:5000/api/products");
or you should run your react app on port 5000

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