How to receive JSON Object from node and display it on client side in react? - node.js

I am sending a json object using res.json. On the client side I am trying to set the json object to a piece of state.
Ive tried to .json() the response but that still does not let me assign it.
This is the server side sending the JSON File
app.get('/api/getPlace', async (req, res) => {
const response = await client.search({
searchType: "Coffee",
location: "San Francisco, CA",
})
const foodPlace = response.jsonBody.businesses[9];
console.log(foodPlace);
res.json(foodPlace)
})
Below is the whole component file to render the json object
import React, { Component } from 'react';
import axios from 'axios';
class RandomPlace extends Component {
constructor(props) {
super(props);
this.state = {
response: {},
};
}
async componentDidMount() {
const res = axios.get('/api/getPlace');
this.setState({ response: res.data })
}
render() {
return (
<div>
{this.state.response}
</div>
);
}
}
export default RandomPlace;

The client call must be awaited:
async componentDidMount() {
const res = await axios.get('/api/getPlace');
this.setState({ response: res.data })
}

import React, { Component } from 'react';
import axios from 'axios';
class RandomPlace extends Component {
constructor(props) {
super(props);
this.state = {
response: {},
};
}
async componentDidMount() {
const res = await axios.get('/api/getPlace');
this.setState({ response: res.data })
}
render() {
return (
<div>
{this.state.response}
</div>
);
}
}
export default RandomPlace;
REST api calls are asynchronous, which means the code proceeds to the next statement without waiting for the api call to compelete. When await is adding before the call, the execution will pause till the call completes or timesout (if specified) before proceeding to the next line. async/await is a better alternative to promises.

Related

I'm fetching dynamic data from my nodejs to reactjs but I get an error saying "POST IS NOT DEFINED"

I have made entries in my mongodb database using node now I'm trying to fetch that data from backend to react front-end the 3rd party app used for cross-platform in node are cors and for react is axios(in script I have added "proxy":"http://localhost:5000"(5000 is my backend port)
Here is my code for NovelCard.js
import React, { Component } from 'react';
import { Container } from 'react-bootstrap';
import Card from 'react-bootstrap/Card';
import axios from 'axios';
const createSet = (post) => {
<Card style={{ width: '18rem' }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>{post.name}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">{post.author}</Card.Subtitle>
<Card.Text>{post.synopsis}</Card.Text>
</Card.Body>
</Card>;
};
class Latest extends Component {
state = {
name: '',
author: '',
synopsis: '',
post: [],
};
componentDidMount = () => {
this.getData();
};
getData = () => {
axios
.get('http://localhost:5000/novels/')
.then((res) => {
const data = res.data;
this.setState({ post: data });
console.log('data recived');
})
.catch(() => {
alert('error');
});
};
render() {
console.log('state', this.state);
return <Container>{post.map(createSet)}</Container>;
}
}
export default Latest;
I'm getting error saying ***
src\components\home\Latest\NovelCard.js Line 45:24: 'post' is not
defined no-undef
Your post variable is available within you state. You need to do something like this within your render function.
render() {
console.log('state', this.state);
return <Container>{this.state.post.map(createSet)}</Container>;
}
Or you can do like this as well.
render() {
const { post } = this.state;
console.log('state', this.state);
return <Container>{post.map(createSet)}</Container>;
}

Problem requesting data based on URL parameters in React-Redux

On a MERN-stack application, I would like to request data from a particular user's schema based on the url parameters. For instance, http://localhost:3000/user/User1 would render data from User 1. I am using redux-react for state management. Here is what I currently have, and here is what's happening.
Userpage Component
import React, { Component } from "react";
import {getUser} from '../../actions/userActions';
import {connect} from 'react-redux'
class Userpage extends Component {
componentDidMount() {
getUser(this.props.match.params.username)
}
render() {
return (
<div>
<h1>Hello</h1>
<h3>{this.props.user.name}</h3>
<h3>{this.props.user.email}</h3>
</div>
);
}
}
const mapStatetoProps = state => {
return{user: state.user}
};
export default connect(mapStatetoProps, getUser) (Userpage)
userActions
import axios from 'axios';
import {GET_USER} from './types';
export const getUser = username => dispatch => {
axios
.get(`/api/users/${username}`)
.then(({res}) =>
dispatch({
type: GET_USER,
payload: username
})
)
};
userReducer
import { GET_USER } from "../actions/types";
const initialState = {
user: {},
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_USER:
return{
...state,
user: action.payload,
}
}
Then in the api/users route, I have the following:
router.get("/:username", (req, res) => {
User.findOne({username: req.params.username})
.then(user => res.json(user))
});
Beyond the user state returning as empty, here are some errors I am getting.
On the command line, I occasionally get a
Could not proxy request /api/users/function%20(action)%20%7B%20%20%20%20%20%20%20%20if%20(typeof%20action%20===%20'function')%20%7B%20%20%20%20%20%20%20%20%20%20return%20action(dispatch,%20getState,%20extraArgument);%20%20%20%20%20%20%20%20%7D%20%20%20%20%20%20%20%20return%20next(action);%20%20%20%20%20%20%7D from localhost:3000 to http://localhost:5000.
As well as a
mapDispatchToProps() in Connect(Userpage) must return a plain object. Instead received undefined.
Any help or guidance would be greatly appreciated.

TypeError: Cannot read property 'map' of undefined in reactjs

I'm working on an app with expressjs and reactjs. I fetched the data from the backend using expressjs but I get map is not a function.
import React, { Component } from "react";
import "./products.css";
import Listofproducts from "./listofproducts";
import { Link } from "react-router-dom";
class products extends Component {
constructor(props) {
super(props);
this.state = {
productInfo: ""
};
}
async getProducts() {
try {
const data = await fetch("http://localhost:4000/product");
const jsonData = await data.json();
this.setState({
productInfo: jsonData
});
console.log(this.state.productInfo);
} catch (error) {
console.log(error);
}
}
componentDidMount() {
this.getProducts();
}
render() {
return (
<React.Fragment>
<Listofproducts itemlists={this.state.productInfo} />
</React.Fragment>
);
}
}
export default products;
Here is the component productLists where I sent the props to work with it.
import React, { Component } from "react";
import Product from "./products";
class Listofproducts extends Component {
render() {
const { itemslist } = this.props;
console.log(itemslist);
// console.log is working here i get back the data on the console
return itemslist.map(list => {
console.log(list);
});
}
}
export default Listofproducts;
You set productInfo to an empty string in the constructor of products, and strings don't have a map method.
Change the default value to an empty array instead and it will work just as well before and after your network request completes.
class Products extends Component {
constructor(props) {
super(props);
this.state = {
productInfo: []
};
}
// ...
}

getInitialProps does not work when the page reload

I'm using getInitialProps in the _app.js component, but when I reload the page, the request does not execute.
For example:
// getData.js
import * as axios from 'axios';
export default async function getData() {
const response = await axios.get('http://someapi.com/');
return response.data;
}
And then I'm going to use that data...
// _app.js
import getData from './getData';
import App, { Container } from "next/app";
class MyApp extends App {
static async getInitialProps() {
const response = await getData();
if (response) {
return { response };
}
return {};
}
render() {
const { Component, response } = this.props;
<Container>
<Component {...this.props} data={response} />
</Container>
}
}
The first time, it works perfectly, but when I reload the page the getInitialProps() function does not executes :(
How can I resolve this?
Thank you.

Sending a String from Node Js to a component React Js

i am using Node Js and React Js to send data from node to a React component but the state never change in the console when i did response.json() i get my string sent but in my component it's empty and there is no data .
Here is my Node js code :
app.post('/try', function(req, res) {
results='hello everybody !'
res.send(JSON.stringify(results));
});
And here's my React component:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = { results: null };
}
componentDidMount() {
const data = new FormData();
fetch('http://localhost:4000/try',{
method: 'POST',
body : data
})
.then(
(response) => {
console.log(response);
return response.json();
} // if the response is a JSON object
).then(
success =>console.log(success) // Handle the success response object
).catch(
error => null // Handle the error response object
)
.then(results => {
this.setState({ results: results });
console.log(results)
});
}
render() {
return (
<div className="Users">
<h1>results</h1>
<div>this is my result: {this.state.results}</div>
</div>
);
}
}
export default App;
First of all, results is string, you dont have to convert it to string again,
results='hello everybody !'
then, in react you are not using the proper way of thens. Please try the below code.
fetch('http://localhost:4000/try', {
method: 'POST',
body: data
})
.then((response) => {
console.log(response);
response.json().then((result)=>this.setState({ results: results }))
}
.catch(
error => null // Handle the error response object
)
You can't convert the normal string to JSON.
eg.
var result = "hello everybody !"
console.log(JSON.stringify(result)); // ""hello everybody !""
This is not a JSON
Try this way
var result = {"data" :"hello everybody !"}
console.log(JSON.stringify(result)); // "{"data":"hello everybody !"}"

Resources