React JS doesn't render on first time - reactjs

import React, { useState, useRef, useEffect } from "react";
import fire from "../../../config";
import { useAuth } from "../../AuthContext";
import { Grid, Paper, Typography } from "#material-ui/core";
import "./style.css";
import { Link } from "react-router-dom";
import UserReviewComponent from "./UserReviewComponent";
import ReviewComponent from "../Reviews/ReviewComponent";
import ReactPaginate from "react-paginate";
export default function UserReviews() {
const [reviews, setReviews] = useState([]);
const [photo, setPhoto] = useState();
const [state, setstate] = useState();
const { currentUser } = useAuth();
const refItem = fire.firestore().collection("User");
const [loading, setLoading] = useState([true]);
const [vendorDetails, setVendorDetails] = useState([]);
const [error, setError] = useState(0);
const [value, setValue] = useState(0);
const [rating, setRating] = useState(0);
useEffect(() => {
fetchUserDetails();
fetchUserReviews();
}, []);
const [users, setUsers] = useState([]);
const [pageNumber, setPageNumber] = useState(0);
const usersPerPage = 2;
const pagesVisited = pageNumber * usersPerPage;
const pageCount = Math.ceil(users.length / usersPerPage);
const changePage = ({ selected }) => {
setPageNumber(selected);
};
const displayUsers = users
.slice(pagesVisited, pagesVisited + usersPerPage)
.map((v) => {
return (
<ReviewComponent
vendorid={v.vendorId}
rating={v.rating}
review={v.review}
useremail={v.useremail}
username={v.username}
userid={v.userid}
date={v.date}
id={v.id}
/>
);
});
const fetchUserReviews = () => {
fire
.firestore()
.collection("VendorReviews")
.where("useremail", "==", currentUser.email)
.get()
.then((querySnapshot) => {
const item = [];
querySnapshot.forEach((doc) => {
item.push(doc.data());
});
setReviews(item);
setUsers(reviews.slice(0, 50));
});
};
const fetchUserDetails = () => {
refItem.doc(currentUser.email).onSnapshot((doc) => {
if (doc.exists) {
setstate(doc.data().status);
setPhoto(doc.data().photourl);
} else {
console.log("No such document!");
}
});
};
// const getTotalUserRating = () => {
// let totalRating = 0;
// reviews.map((v) => {
// totalRating += v.rating;
// });
// setRating(totalRating);
// setLoading(false);
// };
// if (loading) {
// return <div className="App">Loading...</div>;
// }
return (
<>
<div className="container-1">
<div className="row">
<div className="col-md-12">
<div id="content" className="content content-full-width">
<div className="profile-1">
<div className="profile-header">
<div className="profile-header-cover"></div>
<div className="profile-header-content">
<div className="profile-header-img">
<img src={photo} alt="" />
</div>
<div className="profile-header-info">
<h4 className="m-t-10 m-b-5">
{currentUser.displayName}
</h4>
<p className="m-b-10">{state}</p>
<Link
to={`/user/${currentUser.uid}`}
className="btn btn-sm btn-info mb-2"
>
Edit Profile
</Link>
</div>
</div>
<ul className="profile-header-tab nav nav-tabs">
<li className="nav-item">
<a
href="#profile-post"
className="nav-link active show"
data-toggle="tab"
>
My Reviews
</a>
</li>
</ul>
</div>
</div>
<div className="container">
<div className="col-md-12">
<div className="offer-dedicated-body-left">
<div className="tab-content" id="pills-tabContent">
<div
className="tab-pane fade active show"
id="pills-reviews"
role="tabpanel"
aria-labelledby="pills-reviews-tab"
>
<div className="bg-white rounded shadow-sm p-4 mb-4 restaurant-detailed-ratings-and-reviews">
<h5 className="mb-1">All Ratings and Reviews</h5>
{displayUsers}
<hr />
<hr />
<a
className="text-center w-100 d-block mt-4 font-weight-bold"
href="#"
>
<ReactPaginate
previousLabel={"Previous"}
nextLabel={"Next"}
pageCount={pageCount}
onPageChange={changePage}
containerClassName={"paginationBttns"}
previousLinkClassName={"previousBttn"}
nextLinkClassName={"nextBttn"}
disabledClassName={"paginationDisabled"}
activeClassName={"paginationActive"}
/>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
);
}
If I edit something on the IDE and then save and then the content appears but there is nothing on the first render. Please help me out. I think its due to pagination and the array has undefined values on the first render and so it returns nothing. The pagination slices the array so that the pagination is implemented.

add following in useEffects dependency array
useEffect(() => {
fetchUserDetails();
fetchUserReviews();
}, [reviews, state, photo, users ]);

Related

I want my button to increase my products but I am getting two problems

The first problem is when I use:
const [visible, setVisible] = useState(4);
and put it in:
products.slice(0, visible)
It is showing me all the products rather than 4. This issue doesn't occur when I use it like this:
products.slice(0, 4)
The second problem is that I want my button "Load More" to increase value of Visible but it is not working.
Here is the complete code:
import React, {useEffect, useState} from 'react'
import './ForYou.css'
import ForYouItem from './ForYouItem'
export default function ForYou(props) {
const [products, setProducts] = useState([]);
const [visible, setVisible] = useState(4);
useEffect(() => {
fetch('https://fakestoreapi.com/products')
.then((res) => res.json())
.then((data) => setProducts(data))
}, [])
const showMoreItems = () => {
setVisible((prevValue) => prevValue + 4)
}
return (
<div>
<div className="ForYou-container">
<div className="heading">
<a href="#" className='Big-text'> {props.Bigheading}</a>
</div>
<div className="row ">
{products.slice(0, visible).map((product) => {
return(
<div className="col-md-3 my-2 Products">
<ForYouItem Title={product.title.slice(0,50)} Price={product.price} Imageurl = {product.image}/>
</div>
)
}
)}
<button className='Load-btn' onClick={showMoreItems}>Load More</button>
</div>
</div>
</div>
)
}
Code for child component:
import React from 'react'
import './ForYouItem.css'
export default function ForYouItem(props) {
return (
<div>
<a href="#">
<div class="card" >
<img src={props.Imageurl} class="card-img-top" alt="..."/>
<div class="card-body">
<h5 class="card-title"> {props.Title}... </h5>
<p class="card-text">Rs.{props.Price}</p>
Buy Now!
</div>
</div>
</a>
</div>
)
}
I have tried your code and make a few modifications since there was no code for the child component so I can make it work. However I did not find any errors, check this code to see if you get any ideas on how to implement the increasing of the items and check the ForYouItems component as there might be the issue since it renders ok with less data.
import React, {useEffect, useState} from 'react'
const ForYouItem = ({Title})=>{
return <>
<div>{Title}</div>
</>
}
export default function ForYou(props) {
const [products, setProducts] = useState([]);
const [visible, setVisible] = useState(4);
useEffect(() => {
fetch('https://fakestoreapi.com/products')
.then((res) => res.json())
.then((data) => setProducts(data))
}, [])
const showMoreItems = () => {
setVisible((prevValue) => prevValue + 4)
}
return (
<div>
<div className="ForYou-container">
<div className="heading">
<a href="#" className='Big-text'>props.Bigheading</a>
</div>
<div className="row ">
{products.slice(0, visible).map((product) => {
return(
<div className="col-md-3 my-2 Products">
<ForYouItem Title={product.title.slice(0,50)} />
</div>
)
}
)}
{
visible <= products.length-1 &&
<button className='Load-btn' onClick={showMoreItems}>Load More</button>
}
</div>
</div>
</div>
)
}

Use State not updating as expected

Fairly new to react and trying to build a clone of The Movie Database site. I want this toggle switch to change my api call from movies to tv. It starts working after a couple clicks, but then it throws everything off and it's not displaying the correct items anyway. Not really sure what's going on here...or even why it starts working after two clicks. Anyone know whats up with this?
import React, { useState, useEffect } from "react";
import axios from "axios";
import API_KEY from "../../config";
const Popular = ({ imageUri }) => {
// GET POPULAR MOVIES
const [popularMovies, setPopularMovies] = useState("");
const [genre, setGenre] = useState("movie");
console.log(genre);
const getPopular = async () => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${genre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, []);
const listOptions = document.querySelectorAll(".switch--option");
const background = document.querySelector(".background");
const changeOption = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
getPopular();
listOptions.forEach((option) => {
option.classList.remove("selected");
});
el = el.target.parentElement.parentElement;
let getStartingLeft = Math.floor(
listOptions[0].getBoundingClientRect().left
);
let getLeft = Math.floor(el.getBoundingClientRect().left);
let getWidth = Math.floor(el.getBoundingClientRect().width);
let leftPos = getLeft - getStartingLeft;
background.setAttribute(
"style",
`left: ${leftPos}px; width: ${getWidth}px`
);
el.classList.add("selected");
};
return (
<section className="container movie-list">
<div className="flex">
<div className="movie-list__header">
<h3>What's Popular</h3>
</div>
<div className="switch flex">
<div className="switch--option selected">
<h3>
<a
data-genre="movie"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
In Theaters
</a>
</h3>
<div className="background"></div>
</div>
<div className="switch--option">
<h3>
<a
data-genre="tv"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
On TV
</a>
</h3>
</div>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies &&
popularMovies.map((movie, idX) => (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + "w500" + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
))}
</div>
</div>
</div>
</section>
);
};
export default Popular;
You're using the array index as your key prop when you're mapping your array.
You should use an id that is specific to the data that you're rendering.
React uses the key prop to know which items have changed since the last render.
In your case you should use the movie id in your key prop instead of the array index.
popularMovies.map((movie) => (
<div key={movie.id} className="card">
<div className="image">
<img src={imageUri + 'w500' + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
));
Also
You're calling the api directly after setGenre. However state changes aren't immediate. So when you're making your api call you're still sending the last movie genre.
Two ways of fixing this:
You could call your function with the genre directly, and change your function so it handles this case:
getPopular('movie');
Or you could not call the function at all and add genre as a dependency of your useEffect. That way the useEffect will run each time the genre change.
useEffect(() => {
getPopular();
}, [genre]);
PS: You should consider splitting your code into more component and not interacting with the DOM directly.
To give you an idea of what it could look like, I refactored a bit, but more improvements could be made:
const Popular = ({ imageUri }) => {
const [popularMovies, setPopularMovies] = useState('');
const [genre, setGenre] = useState('movie');
const getPopular = async (movieGenre) => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${movieGenre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, [genre]);
const changeHandler = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
};
const isMovieSelected = genre === 'movie';
const isTvSelected = genre === 'tv';
return (
<section className="container movie-list">
<div className="flex">
<MovieHeader>What's Popular</MovieHeader>
<div className="switch flex">
<Toggle onChange={changeHandler} selected={isMovieSelected}>
In Theaters
</Toggle>
<Toggle onChange={changeHandler} selected={isTvSelected}>
On TV
</Toggle>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies.map((movie) => {
const { title, id, poster_path } = movie;
return (
<MovieItem
title={title}
imageUri={imageUri}
key={id}
poster_path={poster_path}
/>
);
})}
</div>
</div>
</div>
</section>
);
};
export default Popular;
const Toggle = (props) => {
const { children, onChange, selected } = props;
const className = selected ? 'switch--option selected' : 'switch--option';
return (
<div className={className}>
<h3>
<a
data-genre="movie"
onClick={onChange}
className="switch--anchor"
>
{children}
</a>
</h3>
<div className="background"></div>
</div>
);
};
const MovieHeader = (props) => {
const { children } = props;
return (
<div className="movie-list__header">
<h3>{children}</h3>
</div>
);
};
const MovieItem = (props) => {
const { title, imageUri, poster_path } = props;
return (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + 'w500' + poster_path} />
</div>
<p>{title}</p>
</div>
);
};

Why is my fetched data not appearing in my React hooks component?

I am trying to load data into my component for it to be displayed. I thought the issue was that I wasn't using async/await for the fetch, but even after adding that it still is not loading. I am logging out the "offerings" and it is just showing the empty array. How do I keep the component from rendering until after the data is loaded??
Thanks in advance!
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(await res.json());
console.log(offerings, 'offerings')
};
useEffect(async () => {
navbarToggle();
await loadData();
}, []);
const dispatch = useDispatch();
const modalState = useSelector((state) => state.modal);
const modalToggle = () => {
dispatch({
type: MODAL_TOGGLE,
payload: !modalState.show,
});
ga.event("navbar_requestdemo_clicked");
};
const navbarOpenState = useSelector((state) => state.navbar);
const navbarToggle = () => {
if (!navbarOpenState.open) return;
dispatch({
type: NAVBAR_OPEN,
payload: false,
});
};
return (
<div
className="d-flex justify-content-center align-items-center bg-color-white fc-px-15"
onClick={navbarToggle}
>
<div className={homeStyles["padded-body"] + " col-11 p-0"}>
<div className=" position-relative bg-color-white">
<div className={homeStyles["img-holder"]}></div>
<div className="col-12 column position-absolute top-0 d-flex justify-content-center">
<div className="col-lg-6 col-12 fc-mt-2">
<SearchBar />
</div>
</div>
<div className="position-absolute top-50 translateY-middle">
<div className="position-relative">
<h1 className={`${homeStyles["hero-text"]} font-weight-bolder`}>
Building
<br />
Meaningful
<br />
Engagement
</h1>
<button
className="btn btn-primary-round mt-3 px-3 py-2"
onClick={() => {
modalToggle();
}}
>
Request access
</button>
</div>
</div>
</div>
<div
id={homeStyles["discover-section"]}
className="d-flex justify-content-center align-items-center"
>
<div className="col-12 column">
<h4 className="font-weight-bold">Discover</h4>
<div
id={homeStyles["offer-section"]}
className="row justify-content-center align-items-center"
>
{!offerings?.length &&
<h4 className="text-center">There are no active offerings.</h4>
}
</div>
<OfferingCarousal
offeringsList={offerings}
name={"Offerings"}
/>
<div id={homeStyles["consultancy-section"]} className="">
<div className="row">
<div
className="d-flex justify-content-center align-items-center col-lg-6 col-12 px-0 mt-3 mb-4"
id={homeStyles["consultancy-div"]}
>
<div className="col-12 column p-5">
<h1 className="font-weight-bold">Add your consultancy</h1>
<h5 className="mt-4">
Reach more people and organizations
</h5>
<Link href="/consultancies">
<button className="btn btn-primary-round mt-4">
Learn more
</button>
</Link>
</div>
</div>
<div className="col-lg-6 col-12 px-0">
<img
src="/images/Rachael_glasses_home_page.jpg"
id={homeStyles["consultant-img"]}
className="mt-3"
/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default HomeNew;
You can check if the data is present before you consume the data.
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(res.json());
console.log(res, 'offerings')
};
useEffect(() => {
navbarToggle();
loadData(); // await has no affect inside useEffect for top level functions
}, []);
// removed internal code for clarity
const dispatch = useDispatch(...yourCode);
const modalState = useSelector(...yourCode);
const modalToggle = () => {...yourCode};
const navbarOpenState = useSelector(...yourCode);
const navbarToggle = () => {...yourCode};
// check after the hooks and before the consuming the data
if(!offerings && !offerings.length) return <>No offerings</>;
return <div>your side nav</div>;
};
It's also good practice to catch asynchronous errors as they occur to prevent your a single component form breaking your whole app. You can also take advantage of the try...catch and put in loading and error states too.
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
try {
setError(false);
setLoading(true);
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(res.json());
} catch (e){
setError(true)
} finally {
setLoading(false);
}
};
// other code from above
if(error) return <>error</>;
if(loading) return <>loading</>;
if(!offerings && !offerings.length) return <>No offerings</>;
return <div>your side nav</div>;
};
async function can't be put in the useEffect hook directly.
https://prnt.sc/1lu7vdc
It can be like this.
useEffect(() => {
...
(async ()=>{
await loadData()
})();
}, []);
But in your case, I think you don't need to wait until loadData function is executed.
Just make sure you handle exceptions on the rendering for Empty data.

React question : how to pass an id from a component to another on click?

I need your help with an app that I am building. It has a forum page and I have some issues with the forum and post components.
I am trying to pass the id of the post that the user clicked on, with history.push so on the post page the id in the url that I try to get with useParams, has the value of the one I send with history.push. The purpose is for some queries I do so I show the post with its comments.
For now the layout isn’t great because I have to make this feature work.
I do not understand why it doesn’t. My console.logs show null or undefined which make no sense to me.
Thank you if you can help me with this.
Here you have two routes present in the App component. It is important for the last route, the Post one were I use :id so I can get it with useParams.
{/* Route for Trainings Wakeup Rebirth */}
<Route path='#forum' exact component={TrainingsWakeupRebirth} />
<Route path='#forum/:id' exact component={Post} />
Here you have the entire code of the Forum page. Like that you can see how I use history.push to send the value.id of the post to the Post component and the way the component itself is built.
import React, { useState, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import ReactPaginate from "react-paginate";
import Post from "../Post/Post";
import './TrainingsWakeupRebirth.scss';
import axios from "axios";
const TrainingsWakeupRebirth = (props) => {
let history = useHistory();
// const forumSectionRef = useRef();
// const postSectionRef = useRef();
const forumSection = document.getElementById('forum-block-wrapper');
const postSection = document.getElementById('post-section');
const showPost = () => {
if (forumSection.style.display === 'block') {
return forumSection.style.display = 'none',
postSection.style.display = 'block';
} else {
return forumSection.style.display = 'block',
postSection.style.display = 'none';
}
}
const [listOfPosts, setListsOfPosts] = useState([]);
const [pageNumber, setPageNumber] = useState(0);
const postsPerPage = 2;
const pagesVisited = pageNumber * postsPerPage;
const displayPosts = listOfPosts.slice(pagesVisited, pagesVisited + postsPerPage).map((value, key) => {
const forParams = () => {
return history.push(`#forum/${value.id}`);
}
const executeAll = () => {
forParams();
showPost();
if(forParams()) {
let id = value.id;
return id;
}
}
return (
<div key={key}>
<div className="topic-row" onClick={() => {executeAll()}}>
<div className="topic-title">{value.title}</div>
<div className="topic-image">
<img src={value.image} alt=""></img>
</div>
<div className="topic-message">{value.postText}</div>
</div>
</div>
);
});
const pageCount = Math.ceil(listOfPosts.length / postsPerPage);
const changePage = ({selected}) => {
setPageNumber(selected);
};
useEffect(() => {
axios.get("http://localhost:3001/posts").then((response) => {
setListsOfPosts(response.data);
});
}, []);
console.log(listOfPosts);
return (
<div className="forum" id="forum">
<div className="forum-section-wrapper page" id="forum-wrapper">
<div className="fluid-grid">
<div className="row">
<div className="col-12">
<div className="title">
<h1><span className="first-title-part">Krishna</span><span className="second-title-part">Hara</span></h1>
</div>
<div className="quote">
<span className="quote-left">FORUM</span><span className="quote-right">Eco Village</span>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="forum-block-wrapper" id="forum-block-wrapper">
{displayPosts}
<ReactPaginate
previousLabel={"Previous"}
nextLabel={"Next"}
pageCount={pageCount}
onPageChange={changePage}
containerClassName={"paginationBttns"}
previousLinkClassName={"previousBttn"}
nextLinkClassName={"nextBttn"}
activeClassName={"paginationActive"}
/>
</div>
</div>
</div>
</div>
</div>
<div className="post-section" id="post-section">
<div className="fluid-grid">
<div className="row">
<div className="col-12">
<Post />
</div>
</div>
</div>
</div>
</div>
)
};
export default TrainingsWakeupRebirth;
Here is some code from the Post component, so you can see the code that should work but doesn't. Also the console.log(id)
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
const Post = (props) => {
let { id } = useParams();
const [postObject, setPostObject] = useState({});
const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState("");
console.log(id);
useEffect(() => {
axios.get(`http://localhost:3001/posts/byId/${id}`).then((response) => {
console.log(response);
setPostObject(response.data);
});
axios.get(`http://localhost:3001/comments/${id}`).then((response) => {
setComments(response.data);
});
}, [id]);
const addComment = () => {
axios.post("http://localhost:3001/comments", {
commentBody: newComment,
Postid: id,
})
.then((response) => {
const commentToAdd = { commentBody: newComment };
setComments([...comments, commentToAdd]);
setNewComment("");
});
};
console.log(postObject);
return (
<div className="post-section-wrapper">
{/* <div>
<div className="title">
{postObject.title}
</div>
<div className="image">
<img src={postObject.image}></img>
</div>
<div className="message">
{postObject.postText}
</div>
</div> */}
<div className="comments-wrapper">
<div className="">
<input
type="text"
placeholder="Comment..."
autoComplete="off"
value={newComment}
onChange={(event) => {
setNewComment(event.target.value);
}}
/>
<button onClick={addComment}> Add Comment</button>
</div>
<div className="comments-row">
{comments.map((comment) =>
(
<div key={comment.id} className="comment">
{comment.commentBody}
</div>
)
)}
</div>
</div>
</div>
);
}
export default Post;
Thank you very very much!!!
#DrewReese and #JoelHager Thank you so much for checking my code and for your advice. In the meantime I found out that we can pass to a component, aside from the pathname, other values with history.push that we retrieve by using useLocation in the component that we want to. I will answer my own question and add the code.
Here is my Forum component, I prefer adding the entire code so everything is clear. In forParams you will see how I pass the value that I need with useHistory and the attribute state and detail.
import React, { useState, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import ReactPaginate from 'react-paginate';
import Post from '../Post/Post';
import './TrainingsWakeupRebirth.scss';
import axios from 'axios';
const TrainingsWakeupRebirth = (props) => {
let history = useHistory();
// const forumSectionRef = useRef();
// const postSectionRef = useRef();
const forumSection = document.getElementById('forum-block-wrapper');
const postSection = document.getElementById('post-section');
const showPost = () => {
if (forumSection.style.display === 'block') {
return forumSection.style.display = 'none',
postSection.style.display = 'block';
} else {
return forumSection.style.display = 'block',
postSection.style.display = 'none';
}
}
const [listOfPosts, setListsOfPosts] = useState([]);
const [pageNumber, setPageNumber] = useState(0);
const postsPerPage = 2;
const pagesVisited = pageNumber * postsPerPage;
const displayPosts = listOfPosts.slice(pagesVisited, pagesVisited + postsPerPage).map((value, key) => {
const forParams = () => {
history.push(
{
pathname: `#forum#${value.id}`,
state: { detail: value.id }
}
);
}
const executeAll = () => {
forParams();
showPost();
}
return (
<div key={key} onClick={() => {executeAll()}}>
<div className="topic-row">
<div className="topic-title">{value.title}</div>
<div className="topic-image">
<img src={value.image} alt=""></img>
</div>
<div className="topic-message">{value.postText}</div>
</div>
</div>
);
});
const pageCount = Math.ceil(listOfPosts.length / postsPerPage);
const changePage = ({selected}) => {
setPageNumber(selected);
};
useEffect(() => {
axios.get("http://localhost:3001/posts").then((response) => {
setListsOfPosts(response.data);
});
}, []);
console.log(listOfPosts);
return (
<div className="forum" id="forum">
<div className="forum-section-wrapper page" id="forum-wrapper">
<div className="fluid-grid">
<div className="row">
<div className="col-12">
<div className="title">
<h1><span className="first-title-part">Krishna</span><span className="second-title-part">Hara</span></h1>
</div>
<div className="quote">
<span className="quote-left">FORUM</span><span className="quote-right">Eco Village</span>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="forum-block-wrapper" id="forum-block-wrapper">
{displayPosts}
<ReactPaginate
previousLabel={"Previous"}
nextLabel={"Next"}
pageCount={pageCount}
onPageChange={changePage}
containerClassName={"paginationBttns"}
previousLinkClassName={"previousBttn"}
nextLinkClassName={"nextBttn"}
activeClassName={"paginationActive"}
/>
</div>
</div>
</div>
</div>
</div>
<div className="post-section" id="post-section">
<div className="fluid-grid">
<div className="row">
<div className="col-12">
<Post />
</div>
</div>
</div>
</div>
</div>
)
};
export default TrainingsWakeupRebirth;
In the Post component with useLocation and useEffect I get location.state.detail which is the id of the Post, that with useState I set to the constant postId.
import React, { useEffect, useState } from "react";
import { useParams, useHistory, useLocation } from "react-router-dom";
import axios from "axios";
import './Post.scss';
const Post = (props) => {
// let { id } = useParams();
const location = useLocation();
const [postId, setPostId] = useState();
useEffect(() => {
console.log(location.pathname); // result: '#id'
if(location.state) {
console.log(location.state.detail); // result: postId
setPostId(location.state.detail);
}
}, [location]);
const [postObject, setPostObject] = useState({});
const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState("");
// console.log(id);
useEffect(() => {
axios.get(`http://localhost:3001/posts/byId/${postId}`).then((response) => {
console.log(response.data);
setPostObject(response.data);
});
axios.get(`http://localhost:3001/comments/${postId}`).then((response) => {
setComments(response.data);
});
}, [postId]);
const addComment = () => {
axios.post("http://localhost:3001/comments", {
commentBody: newComment,
Postid: postId,
})
.then((response) => {
const commentToAdd = { commentBody: newComment };
setComments([...comments, commentToAdd]);
setNewComment("");
});
};
if(postObject !== null) {
console.log(postObject);
}
return (
<div className="post-section-wrapper">
{postObject !== null
?
<div className="posts-wrapper">
<div className="title">
{postObject.title}
</div>
<div className="image">
<img src={postObject.image}></img>
</div>
<div className="message">
{postObject.postText}
</div>
</div>
:
null
}
<div className="comments-wrapper">
<div className="">
<input
type="text"
placeholder="Comment..."
autoComplete="off"
value={newComment}
onChange={(event) => {
setNewComment(event.target.value);
}}
/>
<button onClick={addComment}> Add Comment</button>
</div>
<div className="comments-row">
{comments.map((comment) =>
(
<div key={comment.id} className="comment">
{comment.commentBody}
</div>
)
)}
</div>
</div>
</div>
);
}
export default Post;

How do I open my react-modal through a component?

I have a component that is a modal for login, but I'm not able to call it this is the code of the component:
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
const INITIAL_USER = {
email: '',
password: ''
}
const ModalLogin = () => {
const [user, setUser] = React.useState(INITIAL_USER);
const [disabled, setDisabled] = React.useState(true);
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState('');
const [modalIsOpen, setIsOpen] = React.useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
React.useEffect((modal) => {
const isUser = Object.values(user).every(el => Boolean(el));
isUser ? setDisabled(false) : setDisabled(true)
}, [user]);
const handleChange = (e) => {
const { name, value } = e.target;
setUser(prevState => ({ ...prevState, [name]: value }));
}
const handleSubmit = async e => {
e.preventDefault();
try {
setLoading(true);
setError('');
const url = `${baseUrl}/api/login`;
const payload = { ...user };
const response = await axios.post(url, payload);
handleLogin(response.data);
} catch (error) {
catchErrors(error, setError);
} finally {
setLoading(false);
}
}
const customStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)'
}
};
return (
<Modal
isOpen={modalIsOpen}
style={customStyles}
onRequestClose={closeModal}
>
<div className="theme_login">
<div className="theme_login_box radius">
<header>
<h1>Fazer Login:</h1>
<p>Informe seu nome e e-mail para fazer login e acessar seus pedidos.</p>
</header>
<form method="POST" onSubmit={handleSubmit}>
<input className="radius" type="email" name="email" value={user.email} onChange={handleChange} placeholder="E-mail:" />
<input className="radius" type="password" name="password" value={user.password} onChange={handleChange} placeholder="Senha:" />
<button className="btn transition radius icon-success" type="submit" href="/" title="Minha conta">Fazer Login</button>
</form>
Esqueci minha senha
</div>
</div>
</Modal>
)
};
export default ModalLogin;
I want to call him through my StaticHeader.js:
import React from 'react';
import Link from "next/link";
import Router, { useRouter } from 'next/router';
import NProgress from 'nprogress';
import { handleLogout } from '../../utils/auth';
import ModalLogin from './ModalLogin';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
Router.onRouteChangeStart = () => NProgress.start();
Router.onRouteChangeComplete = () => NProgress.done();
Router.onRouteChangeError = () => NProgress.done();
const StaticHeader = ({ user }) => {
const router = useRouter();
const [menuActive, setMenuActive] = React.useState(false);
const [search, setSearch] = React.useState({ search: '' });
//console.log(user)
const isRoot = user && user.role == 'root';
const isAdmin = user && user.role == 'admin';
const isRootOrAdmin = isRoot || isAdmin;
const [modalIsOpen, setIsOpen] = React.useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
const isActive = (route) => {
return route == router.pathname;
}
const handleOnChange = (e) => {
const { name, value } = e.target;
setSearch(prevState => ({ ...prevState, [name]: value }))
}
const handleSearch = (e) => {
Router.push({
pathname: '/products',
query: { term: search.search }
})
}
const menuToggle = () => {
setMenuActive(!menuActive)
}
const customStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)'
}
};
return (
<header className="main_header">
<div className="container">
<div className="main_header_nav">
<div className="main_header_nav_logo">
<a href="" title="WdpShoes | Home">
<img alt="logo" title="logo menu" src="/css/themes/logo/wdpshoes_logo_white.png" />
</a>
</div>
<div className="main_header_nav_search">
<form action="" method="post" className="radius">
<input type="text" name="s" placeholder="Pesquisar na loja:" />
<button className="icon-search icon-notext transition"></button>
</form>
</div>
<div className="main_header_nav_menu">
<a className="icon-cart icon-notext transition main_header_nav_menu_cart" href="/cart"><span>3</span></a>
<div className="main_header_nav_menu_user">
<a href="#" title="#" className="icon-user main_header_nav_menu_user_a radius transition" onClick={openModal} >
{modalIsOpen && <ModalLogin/>}
Login</a>
<nav className="radius">
Meus Pedidos
Meus Pedeidos
Meus endereços
Sair
</nav>
</div>
</div>
</div>
<ul className="main_header_departments">
<li className="main_header_departments_li">
Departamento
<ul className="main_header_departments_li_ul">
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
</ul>
</li>
<li className="main_header_departments_li">
Departamento
<ul className="main_header_departments_li_ul">
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
</ul>
</li>
<li className="main_header_departments_li">
Departamento
<ul className="main_header_departments_li_ul">
<li className="main_header_deprtaments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
</ul>
</li>
<li className="main_header_departments_li">
Departamento
<ul className="main_header_departments_li_ul">
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
<li className="main_header_departments_li_ul_li">Categoria</li>
</ul>
</li>
</ul>
</div>
</header>
);
}
export default StaticHeader;
What do I need to do for this modal to appear in my header when clicking on login?
I believe it will be necessary to send the functions through the props I tried a few times without success please could someone help solve this problem?

Resources