Pulling Data From Node.js Rest Api Into React with axios - node.js

I am New to react, Node.js so I apologize if this is simple. I have been trying to pull Data From A Node.js Api Running Express into a React Component with Axios. I have tried many different ways and have searched for a solution with no luck. I am unable to access the Id as well as the ProductName
JSON DATA
{"Results":
[
{"id":4,"productName":"Flap Disc"}, {"id":5,"productName":"Fiber Disc"}
]
}
For whatever reason I am unable to Access the data inside these Objects.
CODE
export default function Parent () {
const [products, setProducts] = React.useState('');
const url = 'http://localhost:3040/';
React.useEffect(()=>{
async function getProduct(){
const response = await axios.get(`${url}`);
const a = (response.data.Results)
setProducts(a.map((item)=>
{item}
))
}
getProduct()
}, [])
return(
<div>
{
console.log(products)
}
</div>
)
}

Logging out inside JSX won't do anything. What you want to do is map over the data and display it as a component. Change your return to something more like this
return (
<div>
{products?.map((product) => <p>{product.name}<p>)
</div>
)
You should also change the default value fo products from an empty string to an empty array
const [products, setProducts] = React.useState([])

Related

MERN blog - how to display posts latest first?

I want to be able to display the newest blog posts first, at the moment when a user adds a post the latest post adds below the previous one - I want the opposite to happen so the newest post is the first post.
import Header from "../../components/header/Header";
import Posts from "../../components/posts/Posts";
import Sidebar from "../../components/sidebar/Sidebar";
import "./home.css";
import axios from "axios";
import { useLocation } from "react-router";
export default function Home() {
const [posts, setPosts] = useState([]);
const { search } = useLocation();
useEffect(() => {
const fetchPosts = async () => {
const res = await axios.get("/posts" + search);
setPosts(res.data);
};
fetchPosts();
}, [search]);
return (
<>
<Header />
<div className="home">
<Posts posts={posts} />
<Sidebar />
</div>
</>
);
}
Thank you!
Ideally sorted data should be served from API response. Your API call would look something like this - /posted?orderBy=createdAt.
If you want to achieve this from client side, you may use array reverse()
method like this - setPosts(res.data.reverse());

Query parameters not received from deep linking - react native(expo) and node js

I am using openAuthSessionAsync to do a call to my backend and sending the url for deep linking
I am redirected back successfully to my app but i don't get query parameters that i send from backend with deep link
My react native app side:
const experiment = async()=>{
try{
let result = await WebBrowser.openAuthSessionAsync(`http://myaddress :3901/api/testig?linkingUri=${Linking.createURL(
"/?",
)}`,);
console.log(result)
}catch(errr){
console.log(errr)
}
}
My node js side:
router.get("/testig",(req,res)=>{
url = req.query.linkingUri
**//url is exp://myaddress:19000/--/?**
res.redirect(url+"?authToken=abc123")
})
I have also tried hard coding the url in backend but it only opens app back but with no parameters
And in my react native side in console i get this:
Object:{
"type":"dismiss",
}
UPDATE: Solved it by setting up eventListener for LINKING as follows
const handleDeepLink = (event)=>{
let data = Linking.parse(event.url)
setdata(data)
if(JSON.parse(data.queryParams.isSuccessful) == true)
{
props.navigation.navigate("thankyou")
}
}
React.useEffect(()=>{
Linking.addEventListener("url",handleDeepLink)
return(()=>{
Linking.removeEventListener("url")
})
},[])
use trycarch in the block to see errors and use var url
code lookslike
router.get("/testig",(req,res)=>{
try {
var url = req.query.linkingUri
return res.redirect(url+"?authToken=abc123")
} catch (e) {
console.log(e)
}
})

Unable to send api response data from express to react after refreshing the page

I'm learning react and node js with express framework and I'm working on a project where I need to retrieve API data from express to react.
I retrieved data from backend express js where I made a simple json value. My backend server.js code is given below.
server.js
const express = require('express')
const app = express()
const PORT = 3001;
app .get('/api/contents',(req,res)=>{
const contents=[
{
"id":0,
"heading":"Joshua Tree Overnight Adventure",
"content":"A sight in the blue sea..."
},
{
"id":1,
"heading":"Catch waves with an adventure guide",
"content":"Lorem.."
},
{
"id":2,
"heading":"Catch waves with an adventure guide",
"content":"Lorem epsum ..."
}
];
res.json(contents)
})
app.listen(PORT,()=>{
console.log("express server is running...")
})
In react app, I used axios to retrieve those values from backend and tried to pass the api values of content with id= 0 as props in "TheLatestArticles" component. I have updated proxy in package.json in react to connect backend. The below code is the mainhomepage component where it is enclosed with TheLatestArticles component with props value
MainHomePage.js
import axios from 'axios';
import {useState,useEffect} from 'react'
function MainHomePage(){
const [content,setContent]=useState([]);
useEffect(()=>{
const fetchPosts = async ()=>{
const res =await axios.get("/api/contents")
setContent(res.data)
console.log(res)
}
fetchPosts()
},[])
return (
<>
<TheLatestArticle content={content} />
</>
);
}
export default MainHomePage;
TheLatestArticle.js
import cardImage from "./../../Images/card.jpg"
import './TheLatestArticleCard.css';
const TheLatestArticleCard=(props)=>{
console.log(props)
return(
<>
<div className="card">
<div className="image">
<img src={cardImage} alt="cardimg"/>
</div>
<div className="content">
<p className="heading">{props.content.heading}</p>
<p className="body-content">{props.content.content}</p>
<div className="details">
<p className="details-info">Travel <span className="details-info-2">/ August 21 2017</span></p>
</div>
</div>
</div>
</>
)
}
export default TheLatestArticleCard;
When I run the application, It displayed all the api values in the screen given below.
I console.log the api values inside useEffect and it displayed all the api values perfectly.
But when I refresh the page, the api value became undefined and gave me this error
Can you please solve me this issue with the reason behind this error? Thanks a lot!
Try it like this
{(content && content.length > 0) && <TheLatestArticle content={content} />}
Since your API call is async there won't be any data in content initially. After a while, your API is called and data is fetched. Then you will have data. To prevent TheLatestArticle to blow up we add some conditions when to show that component. The error in the screenshot is when you try to use a property heading from content where content is empty.
Now with the condition, TheLatestArticle will not render until there is some data.
Update
You are using <TheLatestArticle content={content} /> and content is assumed to be an object. But as per your code, it's an array. If you are not already using content.map((c)=> <TheLatestArticle content={c} />) you should do that.

How can I import an image from the express server to the client (in React)

I'm trying to show an image in react, which is neither a local image (in the client) nor an external image from the web but an image that is in the node.js express server (and I don't want to call it as if it was an external image, because the domain could change and it just doesn't seem right).
I know I can't just import it like I do with a local image in the client because we're speaking about different localhosts. I did try this:
loadImage = async (imageUrl) => {
const response = await fetch(`/api/images/${imageUrl}`);
const data = await response.json();
this.setState({ image: data });
}
componentDidMount() {
const { imageUrl } = this.props;
try {
this.loadImage(imageUrl);
} catch(error) {
console.log("Hay un error: " + error);
}
}
render() {
const { image } = this.state;
return(
<div>
<div>
<img alt="dontknowyet" className="blog-list-image" src={image} // and so on...
{image} does receive the correct path, but the image won't load and the console throws this error:
Not allowed to load local resource: file:///C:/Users/Dafna/Desktop/adrian/proyectos/esteticand/img/t4.jpg
So how can I make it work? and in case that I need to import the image file instead of just the link, how can I do that? (I can't update the state with an image...)
In order to access the path of the image it has to be done through the express server.
For example, if the (backend) server is running on port 4500 and the image is in a folder called images, and the express variable is called app, in the server file you have to use:
app.use(express.static('images'));
and then the image can be accessed in http://localhost:4500/nameoftheimage.jpg.
Do you have the api running on the same port as the React app?
You usually would make them run on different ports. Maybe it's got something to do with it.

Dynamic file names in react native require()

We're working on an app that will allow users to store templates with images on them, and pull those templates up later. This is for an AR environment using Viro on React Native.
We're trying to dynamically load an image into the component, and receiving errors when we require the filepath, which has been set to a variable:
const exampleUri = '/some/uri'
render() {
return(
<Viro3DObject
source={require(exampleUri)}
/>)
}
The URI for the source prop has to be dynamic, as the URIs are pulled from a Database.
We've tried storing the entire request in the database (in models/element.js):
const Sequelize = require('sequelize');
const db = require('../db');
const Element = db.define('element', {
sourceViro3DObject: {
type: Sequelize.STRING
}
});
sourceViro3DObject: `require('../../assets/emoji_heart/emoji_heart.vrx')`
When we called it in the React Native class component:
getObjectData = async () => {
try {
const {data} = await axios.get(`/api/elements/${this.props.elementId}`)
this.setState({sourceViro3DObject: data.sourceViro3DObject})
} catch (err) {
console.log(err)
}
}
async componentDidMount() {
await this.getObjectData()
}
But this simply sets state.sourceViro3DObject to a string:
'require('../../assets/emoji_heart/emoji_heart.vrx')'
We've tried setting the filepath directly to state as a string:
state.sourceViro3DObject = '../../assets/emoji_heart/emoji_heart.vrx'
and then call require on it:
require(this.state.sourceViro3DObject)
and received the following error:
Invalid prop `source` supplied to `Viro3DObject`
We've seen recommendations of storing the URIs in an object, but that can't work for us as we don't know what image is going to be used until it's pulled from the database. We can't hard-code them anywhere.
We'd appreciate any help with this!

Resources