View collections item in Mern - node.js

I have some items in a mongodb collection, now i want to view them on a react app, i've that code, but it doesn't display nothing, but if i check value with a console.log() i get the content. How i can do?
import axios from "axios";
const viewMails = []
axios.get('http://localhost:5000/emails').then(res => {
let emailString = JSON.parse(res.request.response)
for (const [index, value] of Array(emailString).entries()) {
viewMails.push(
<div key={index}>
<h1>{value.name}</h1>
<h3>{value.email}</h3>
<p>{value.message}</p>
<p>{value.createdAt}</p>
</div>
);
}
});
export default class EmailsViewer extends Component {
render() {
return (
<div className="emails">
<h1>Sos</h1>
{viewMails}
</div>
);
}
}```

Since you are trying to do a simple component to show a list, if you're using one of the last version of React, consider using axios hook (check the package documentation to see how to add it to your project https://www.npmjs.com/package/axios-hook)
Here I show you an example of what you need to do: list demo

Related

Load specific DIV with a react component without reloading the whole page

I have a menu where every menu item is a button and I want to load a specific reactjs component into a specific div without reloading the whole page.
This is the current code, clearly is bad but I don't know where to start fixing it...
...
<Button onClick={this.loadTarget}>
{menuItem.name}
</Button>
...
loadTarget(event) {
document.getElementById("datapanel").innerHTML="abc<TranslationsList />";
}
When I click a menu Item I want to load my div with the value "abc<TranslationsList />". "abc" is displayed but the custom component "TranslationsList" is not and I guess this is normal as the TranslationsList tag is not a HTML tag. But how could I load my component?
I could use links instead of buttons but in this case the question is how could I update the div content with a specific link?
It's hard if you've programmed plain JS before, but you have to forget the "good old JS pattern" in React. I also had a hard time getting used to not using standard JS elements (target, innerHTML, etc.) to solve such a problem.
So the solution in React is to use the framework and your page reload problem will be solved immediately. useState for the state of the component and handlers for the click. My main code looks like this. You can find a working application at Codesandbox.
export default function App() {
const [showComponent, setShowComponent] = useState(false);
const handleButtonClick = (e) => {
setShowComponent(!showComponent);
};
return (
<div className="App">
<h1>
Load specific DIV with a react component without reloading the whole
page
</h1>
<a href="https://stackoverflow.com/questions/74654088/load-specific-div-with-a-react-component-without-reloading-the-whole-page">
Link to Stackoverflow
</a>
<div style={{ marginTop: "20px" }}>
<button onClick={handleButtonClick}>Magic</button>
</div>
{showComponent ? (
<div style={{ marginTop: "20px" }}>
This is the place of your component!
</div>
) : (
""
)}
</div>
);
}
In the first place I wpuld not use vanilla JS syntax on a react app if it is not necessary. i.e: document.getElementById("datapanel").innerHTML="abc<TranslationsList />".
If you are using React you should be managing the State in the component of the DIV, giving the order to make an element appear once the button is clicked.
A simple example can be this:
CodeSandbox
import { useState } from "react";
export default function App() {
const [divState, setDivState] = useState(null);
const divElement = () => <div>I am the element that should appear</div>;
const handleDiv = () => {
setDivState(divElement);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={handleDiv}>Show DIV</button>
<div>{divState}</div>
</div>
);
}
I agree with the answers given above. Since you are already using React, you should take advantage of its features/functionalities. No need to reinvent the wheel.
However, if you are still interested in how to make your current implementation work. You may use renderToString(), which can be imported from ReactDOMServer. Please refer to the following code snippet as an example.
import { renderToString } from 'react-dom/server'
const TranslationsList = () => {
return <div>TranslationsList Content</div>
}
export default function App() {
const loadTarget = () => {
document.getElementById("datapanel").innerHTML=`abc${renderToString(<TranslationsList />)}`;
}
return (
<div>
<button onClick={loadTarget}>Insert Component</button>
<div id="datapanel">Data Panel Holder</div>
</div>
);
}

Can you use templates in Next.js?

I am fairly new to web development and currently have a rudimentary web server using Node.js, Express, and Pug which I am hoping to convert to Next.js. Is it possible to create re-usable templates (similar to Pug/Jade) in Next.js?
This is how I do mine. There are better ways, but it's how I like it. I came from express handlebars, and have used pug before, so this is how I did mine.
In pages/_app.js file:
import React from 'react'
import Head from 'next/head'
export default function MyApp({ Component, pageProps }) {
const Layout = Component.Layout || LayoutEmpty // if page has no layout, it uses blank layout
const PageTitle = Component.PageTitle // page title of the page
return (
<Layout>
{PageTitle? (<Head><title>{PageTitle}</title></Head>) : '' }
<Component {...pageProps} />
</Layout>
)
}
const LayoutEmpty = ({children}) => <>{children}</> // blank layout if doesnt detect any layout
In your component folder where ever you want to put your layout file: eg component/layout.js
import Link from 'next/link';
import {useRouter} from 'next/router'
export function LayoutOne({children}) {
try {
return (<>
<nav>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
</ul>
</nav>
<div>{children}</div>
</>)
} catch(e) {console.log(e)}
}
Then in your pages: eg pages/about.js
import React, { useState, useEffect } from 'react';
import {LayoutOne} from '../component/layout' // location of your layout.js file
Aboutpage.PageTitle = 'About | Website Tag Line' // set title of your page
Aboutpage.Layout = LayoutOne // using LayoutOne. If you dont do this, its considered blank layout and you'll get no layout
export default function Aboutpage() {
try {
return (
<>
<div>
<h2>About</h2>
</div>
</>
);
} catch(e) {console.log(e)}
}
If you want more layout, in your layout.js file at the end, just change the name of the export function eg: LayoutTwo
export function LayoutTwo({children}) {
try {
return (<>
<nav>
<ul>
<li><Link href="/dashboard"><a>Dashboard</a></Link></li>
</ul>
</nav>
<div>{children}</div>
</>)
} catch(e) {console.log(e)}
}
And one the page, you change layout to two
import {LayoutTwo} from '../component/layout'
Aboutpage.Layout = LayoutTwo

Passing useState value through parent component using react hooks (getting = undefined)

I'm working in a project already began that's using react class version. I plan to work with react hooks, so to don't refactor all the classes, as I write new codes, I'm trying to mix those react versions (idk if it's a good idea and I should refactor all).
I'm creating a list with pagination and search. The pagination and search are in an unique component.
To this component a need pass the search character value input by user, and here is where I'm facing problem. In other words, I need pass a value to the parent component.
Code is below:
useState hook:
const [search, setSearch] = useState('');
Filter component, that change the search value:
const Filter = () => {
return (
<Card>
<Form.Group label="Filtro">
<Grid.Row gutters="xs">
<Grid.Col>
<Form.Input
name='search'
placeholder='Filtro'
autoFocus
value={search}
onChange={e => setSearch(e.target.value)}
/>
</Grid.Col>
<Grid.Col auto>
<Button
color="success"
icon="search"
onClick={filtrar}
>
</Button>
</Grid.Col>
</Grid.Row>
</Form.Group>
</Card>
);
}
function getSearchDB() {
setSearch((search) => {
return search;
})
}
Pagination component, that receive the props:
<Pagination
baseUrl={'vehicles/toUse'}
updateState={setStateDB}
getSearch={getSearchDB}
fields={'license_plate'}
/>
Printing search value pass through Pagination component:
console.log(this.props.getSearch()) //print undefined
OBS: updateState={setStateDB} is working fine.
Things done to make this work (no success):
In getSearch={getSearchDB} directly pass search value. Result: this.props.getSearch() print undefined
Defined getSearchDB() to be like:
function getSearchDB() {
return search;
}
Result: this.props.getSearch() print undefined.
Is there a way to put it to work?
Guys, let me know if the post is confusion or the English is poorly written.
Instead of passing down a function that returns search, why not just pass down search itself as a prop?
<Pagination
search={search}
const Pagination = (props) => {
console.log(props.search);
add :
<Pagination
search={search}
/>
In component Pagination :
const Pagination = ({search}) => {
console.log(search);
return {
//...
}
}

Why does this return two sets of data?

I have built my firs full stack app that uses a react front end to communicate with a graphql server and surface data up from a mongoDB. When I look at the app from front end it looks like I am making two calls and return two sets of data (actually the same set twice).
Here is what I see in the dev tools console...
It looks to me like the first two are calls out and the last two are the data returns. If you look on the right, those are all to do with line 17 of BookList.js which is this...
console.log(this.props);
and this is the full code of that file....
import React, { Component } from 'react';
import { gql } from 'apollo-boost';
import { graphql } from 'react-apollo';
const getBooksQuery = gql`
{
books {
name
id
}
}
`;
class BookList extends Component {
render(){
console.log(this.props);
return(
<div>
<ul id="book-list">
<li>Book name</li>
</ul>
</div>
);
}
}
export default graphql(getBooksQuery)(BookList);
I am calling that BookList component with this code...
// components
import BookList from './components/BookList';
// apollo client setup
const client = new ApolloClient({
uri: 'http://localhost:5000/graphql'
});
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<div id="main">
<h1>Ninja's Reading List</h1>
<BookList />
</div>
</ApolloProvider>
);
}
}
export default App;
I am unsure why I am getting dbl calls or if that is the expectation. Any guidance at all is appreciated.

how to pass a link to another components in react

I am trying to pass a Link it has a films id to another component named movie detail js.
the problem I am having is connecting Movies Container link to movie detail. Please help
MoviesContainer.js
<Link to={ `/movie/${films.id}${config.apiKey}` }>
<button className='successW' > GET INFO </button>
</Link>
MovieDetail.js
import React, { Component } from 'react';
import axios from 'axios';
import './MovieDetail.css';
import { props , match , params, } from 'react-router-dom';
//import config from '../../config.js';
import films from '../MoviesContainer/MoviesContainer.js';
import router from '../../router.js'
export default class MovieDetail extends Component{
constructor(props){
super(props);
this.state= {
movie:[]
}
}
componentWillMount(){
axios.get(`/movies/:id`).then(response=> {
console.log(response.data.results);
this.setState({ moviesList: response.data.movie });
});
}
render(){
console.log( this.setState.movie);
const imgURL= 'http://image.tmdb.org/t/p/original';
return(
<div className='moviecd'>
<img style={{ height: '85%', width: '100%' }} src={ imgURL + this.state.movie.poster_path } alt='movie poster'></img>
</div>
)
}
}
ı guess you are using React-Router. First of all, you can specify the path you will use in the Router system and which component should be installed if this path is used. For Example :
<Route exact path="/movies/:movieId" component={MovieDetails} />
This is the system you should use for your router.
and there is a button to go to the MovieDetails.js component.
you should wrap this button with a Link(React-Router). Like This:
<Link to = {{pathname: `${movieId}`}}> // The id of the movie you clicked
<button>Go Movie </button>
</Link>
Now, if you clicked on which movie you clicked on, the id of that movie will go to the MovieDetails.js component as a props.
If you browse the props coming to the MovieDetails component, you will find a props like params.match.movieId.
You can now use this id when making a request (Inside the MovieDetails component). Like This:
fetch(`https://api.themoviedb.org/3/movie/${this.props.match.params.movieId}?api_key=<yourapikey>`)
How you process it after you get the data is up to you!
I hope it was understandable. Good Luck !

Resources