I implemented a session timeout function before using class component
It is working fine, however, I want to convert it to functional component and hooks
I'm having trouble especially converting _onAction, onActive, etc.
How do I maintain that the program detects user movement?
Kindly see code below
import React, { Component } from 'react'
import TopNavigation from '../topNavigation'
import SideNavigation from '../sideNavigation'
import Routes from '../Routes'
import Footer from '../Footer'
import IdleTimer from 'react-idle-timer'
import { IdleTimeOutModal } from '../modals/IdleTimeoutModal'
import PropertyService from '../../services/PropertyService'
class AuthenticatedPage extends Component {
constructor(props){
super(props)
this.state = {
timeout: 1000 * 60 * 15, /*15 mins - Initial value only, final is from property file*/
showModal: false,
userLoggedIn: false,
isTimedOut: false
}
this.idleTimer = null
this.onAction = this._onAction.bind(this)
this.onActive = this._onActive.bind(this)
this.onIdle = this._onIdle.bind(this)
this.handleClose = this.handleClose.bind(this)
this.handleLogout = this.handleLogout.bind(this)
}
_onAction(e) {
this.setState({isTimedOut: false})
}
_onActive(e) {
this.setState({isTimedOut: false})
}
_onIdle(e) {
const isTimedOut = this.state.isTimedOut
if (isTimedOut) {
} else {
this.setState({showModal: true})
this.idleTimer.reset();
this.setState({isTimedOut: true})
}
}
handleClose() {
this.setState({showModal: false})
}
handleLogout() {
this.setState({
showModal: false
});
this.props.history.push('/')
}
componentWillMount(){ /* should be called not only once */
PropertyService
.retrieveAllProperties()
.then((response) => {
this.setState({ timeout: response.data.timeout })
})
}
render() {
const { match } = this.props
return (
<React.Fragment>
<IdleTimer
ref={ref => { this.idleTimer = ref }}
element={document}
onActive={this.onActive}
onIdle={this.onIdle}
onAction={this.onAction}
debounce={250}
timeout={this.state.timeout} />
<div>
<TopNavigation />
<SideNavigation />
<main id="content" className="p-5">
<Routes />
</main>
<Footer />
</div>
<IdleTimeOutModal
showModal={this.state.showModal}
handleClose={this.handleClose}
handleLogout={this.handleLogout}
/>
</React.Fragment>
)
}
}
export default AuthenticatedPage
This should work. You can also use useReducer hook if you're feeling that there are too many useState declarations.
import React, { useState, useEffect, useRef } from 'react'
import TopNavigation from '../topNavigation'
import SideNavigation from '../sideNavigation'
import Routes from '../Routes'
import Footer from '../Footer'
import IdleTimer from 'react-idle-timer'
import { IdleTimeOutModal } from '../modals/IdleTimeoutModal'
import PropertyService from '../../services/PropertyService'
const AuthenticatedPage = ({
history
}) => {
const [timeoutDuration, setTimeoutDuration] = useState(1000 * 60 * 15);
const [showModal, setShowModal] = useState(false);
const [userLoggedIn, setUserLoggedIn] = useState(false);
const [isTimedOut, setIsTimedOut] = useState(false);
const idleTimer = useRef();
const onAction = () => {
setIsTimedOut(false);
}
const onActive = (e) => {
setIsTimedOut(false);
}
const onIdle = (e) => {
if (!isTimedOut) {
setShowModal(true)
idleTimer.current.reset();
setIsTimedOut(true);
}
}
const handleClose = () => {
setShowModal(false);
}
const handleLogout = () => {
setShowModal(false);
history.push('/')
}
useEffect(() => {
PropertyService
.retrieveAllProperties()
.then((response) => {
setTimeoutDuration(response.data.timeout);
})
}, []);
return (
<React.Fragment>
<IdleTimer
ref={idleTimer}
element={document}
onActive={onActive}
onIdle={onIdle}
onAction={onAction}
debounce={250}
timeout={timeoutDuration} />
<div>
<TopNavigation />
<SideNavigation />
<main id="content" className="p-5">
<Routes />
</main>
<Footer />
</div>
<IdleTimeOutModal
showModal={showModal}
handleClose={handleClose}
handleLogout={handleLogout}
/>
</React.Fragment>
)
}
export default AuthenticatedPage
Related
import React, { useState } from 'react'
import Display from './components/Display';
const App = () => {
const [input,setInput] = useState("");
const getData = async () => {
const myAPI = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761`);
const response = await myAPI.json();
console.log(response); //want to use response as a prop in Display component
}
return(
<div className="container">
<h1>Weather Report</h1>
<Display title={"City Name :"} /> //here
<Display title={"Temperature :"} /> //here
<Display title={"Description :"} /> //here
<input type={input} onChange={e => setInput(e.target.value)} className="input"/>
<button className="btn-style" onClick={getData}>Fetch</button>
</div>
);
}
export default App;
I don't know if I understand you correctly but if I'm right you want to access data returned from your function that is fetching from API, if so you can try this way
import React, { useState, useEffect } from 'react'
import Display from './components/Display';
import axios from 'axios';
const App = () => {
const [input,setInput] = useState("");
const [state, setState] = useState({loading: true, fetchedData: null});
useEffect(() => {
getData();
}, [setState]);
async function getData() {
setState({ loading: true });
const apiUrl = 'http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761';
await axios.get(apiUrl).then((repos) => {
const rData = repos.data;
setState({ loading: false, fetchedData: rData });
});
}
return(
state.loading ? <CircularProgress /> : (
<List className={classes.root}>
{ state.fetchedData.map((row) => (
<div className="container">
<h1>Weather Report</h1>
<Display title={"City Name :" + row.cityName } /> //here
<Display title={"Temperature :" + row.temperature} /> //here
<Display title={"Description :" + row.description} /> //here
</div>
)) }
</List>
)
);
}
I'm currently struggling with React Context. I'd like to pass functions allowing the show / hide cart logic in the context, instead of using props between components.
I dont understand why when clicking on the button in HeaderCartButton component, it doesn't trigger the **onClick={ctx.onShowCart}** that is in my context, even though when I console log the cartCtx.state it is properly updated, which should then add the component in the App.js
//App.js
import { useContext } from "react";
import Header from "./components/Layout/Header";
import Meals from "./components/Meals/Meals";
import Cart from "./components/Cart/Cart";
import CartProvider from "./store/CartProvider";
import CartContext from "./store/cart-context";
function App() {
const ctx = useContext(CartContext);
return (
<CartProvider>
{ctx.state && <Cart />}
<Header />
<main>
<Meals />
</main>
</CartProvider>
);
}
export default App;
//cart-context.js
import React from "react";
const CartContext = React.createContext({
state: false,
onShowCart: () => {},
onHideCart: () => {},
items: [],
totalAmount: 0,
addItem: (item) => {},
removeItem: (id) => {},
});
export default CartContext;
//CartProvider.js
import CartContext from "./cart-context";
import { useState } from "react";
const CartProvider = (props) => {
const [cartIsShown, setCartIsShown] = useState(false);
const showCartHandler = () => {
setCartIsShown(true);
};
const hideCartHandler = () => {
setCartIsShown(false);
};
const handleAddItem = (item) => {};
const handleRemoveItem = (id) => {};
const cartCtx = {
state: cartIsShown,
onShowCart: showCartHandler,
onHideCart: hideCartHandler,
items: [],
totalAmount: 0,
addItem: handleAddItem,
removeItem: handleRemoveItem,
};
return (
<CartContext.Provider value={cartCtx}>
{props.children}
</CartContext.Provider>
);
};
export default CartProvider;
//Header.js
import { Fragment } from "react";
import HeaderCartButton from "./HeaderCartButton";
import mealsImage from "../../assets/meals.jpg";
import classes from "./Header.module.css";
const Header = (props) => {
return (
<Fragment>
<header className={classes.header}>
<h1>ReactMeals</h1>
<HeaderCartButton />
</header>
<div className={classes["main-image"]}>
<img src={mealsImage} alt="A table full of delicious food!" />
</div>
</Fragment>
);
};
export default Header;
//HeaderCartButton.js
import CartIcon from "../Cart/CartIcon";
import { useContext } from "react";
import classes from "./HeaderCartButton.module.css";
import CartContext from "../../store/cart-context";
const HeaderCartButton = (props) => {
const ctx = useContext(CartContext);
const numberOfCartItems = ctx.items.reduce((accumulator, item) => {
return accumulator + item.amount;
}, 0);
return (
<button className={classes.button} onClick={ctx.onShowCart}>
<span className={classes.icon}>
<CartIcon />
</span>
<span>Your Cart</span>
<span className={classes.badge}>{numberOfCartItems}</span>
</button>
);
};
export default HeaderCartButton;
Thanks for your help
If you look at your App component, you are using CartContext outside the provider.
function App() {
const ctx = useContext(CartContext);
return (
<CartProvider>
{ctx.state && <Cart />}
<Header />
<main>
<Meals />
</main>
</CartProvider>
);
}
You should modify it so that it is similar to the following, where you are using the context inside the provider.
const Main = () => {
return <CartProvider><App /></CartProvider>
}
function App() {
const ctx = useContext(CartContext);
return (
<>
{ctx.state && <Cart />}
<Header />
<main>
<Meals />
</main>
</>
);
}
I am working on a site that has a piece a global state stored in a file using zustand. I need to be able to set that state in a class component. I am able to set the state in a functional component using hooks but I'm wondering if there is a way to use zustand with class components.
I've created a sandbox for this issue if that's helpful:
https://codesandbox.io/s/crazy-darkness-0ttzd
here I'm setting state in a functional component:
function MyFunction() {
const { setPink } = useStore();
return (
<div>
<button onClick={setPink}>Set State Function</button>
</div>
);
}
my state is stored here:
export const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink }))
}));
how can I set state here in a class componet?:
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={
{
/* setPink */
}
}
>
Set State Class
</button>
</div>
);
}
}
A class component's closest analog to a hook is the higher order component (HOC) pattern. Let's translate the hook useStore into the HOC withStore.
const withStore = BaseComponent => props => {
const store = useStore();
return <BaseComponent {...props} store={store} />;
};
We can access the store as a prop in any class component wrapped in withStore.
class BaseMyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { setPink } = this.props.store;
return (
<div>
<button onClick={setPink}>
Set State Class
</button>
</div>
);
}
}
const MyClass = withStore(BaseMyClass);
Seems that it uses hooks, so in class you can work with the instance:
import { useStore } from "./store";
class MyClass extends Component {
render() {
return (
<div>
<button
onClick={() => {
useStore.setState({ isPink: true });
}}
>
Set State Class
</button>
</div>
);
}
}
Create a React Context provider that both functional and class-based components can consume. Move the useStore hook/state to the context Provider.
store.js
import { createContext } from "react";
import create from "zustand";
export const ZustandContext = createContext({
isPink: false,
setPink: () => {}
});
export const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink }))
}));
export const ZustandProvider = ({ children }) => {
const { isPink, setPink } = useStore();
return (
<ZustandContext.Provider
value={{
isPink,
setPink
}}
>
{children}
</ZustandContext.Provider>
);
};
index.js
Wrap your application with the ZustandProvider component.
...
import { ZustandProvider } from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<ZustandProvider>
<App />
</ZustandProvider>
</StrictMode>,
rootElement
);
Consume the ZustandContext context in both components
MyFunction.js
import React, { useContext } from "react";
import { ZustandContext } from './store';
function MyFunction() {
const { setPink } = useContext(ZustandContext);
return (
<div>
<button onClick={setPink}>Set State Function</button>
</div>
);
}
MyClass.js
import React, { Component } from "react";
import { ZustandContext } from './store';
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={this.context.setPink}
>
Set State Class
</button>
</div>
);
}
}
MyClass.contextType = ZustandContext;
Swap in the new ZustandContext in App instead of using the useStore hook directly.
import { useContext} from 'react';
import "./styles.css";
import MyClass from "./MyClass";
import MyFunction from "./MyFunction";
import { ZustandContext } from './store';
export default function App() {
const { isPink } = useContext(ZustandContext);
return (
<div
className="App"
style={{
backgroundColor: isPink ? "pink" : "teal"
}}
>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<MyClass />
<MyFunction />
</div>
);
}
If you aren't able to set any specific context on the MyClass component you can use the ZustandContext.Consumer to provide the setPink callback as a prop.
<ZustandContext.Consumer>
{({ setPink }) => <MyClass setPink={setPink} />}
</ZustandContext.Consumer>
MyClass
<button onClick={this.props.setPink}>Set State Class</button>
This worked out pretty well for me.
:
import React, { Component } from "react";
import { useStore } from "./store";
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={
useStore.getState().setPink() // <-- Changed code
}
>
Set State Class
</button>
</div>
);
}
}
export default MyClass;
I like to create a high order component similar to redux connect:
function connectZustand(useStore, selector) {
return (Component) =>
React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}
eg:
import React, { Component } from 'react';
import create from 'zustand';
import shallow from 'zustand/shallow';
function connectZustand(useStore, selector) {
return (Component) =>
React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}
const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink })),
}));
class MyClass extends Component {
render() {
const { setPink } = this.props;
return (
<div>
<button onClick={() => setPink()}>Set State Class</button>
</div>
);
}
}
const MyClassWithZustand = connectZustand(useStore, (state) => ({ setPink: state.setPink }))(MyClass);
export default function Test() {
const isPink = useStore((state) => state.isPink);
return (
<>
<MyClassWithZustand />
{isPink ? 'Is Pink' : 'Is Not Pink'}
</>
);
}
I am creating my first react project, i am using GitHub api to fetch user and display them firstly in card view then on clicking on more button to any profile i want to create a modal using portals in react till now i am able to create an modal but now i am not getting how to get data to that modal coponent
Here is my App.js
import React, { Fragment, Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Users from './components/users/Users';
import User from './components/users/User';
import Modal from './components/Modal/Modal'
import Search from './components/users/Search';
import Alert from './components/layout/Alert';
import About from './components/pages/About';
import axios from 'axios';
import './App.css';
class App extends Component {
state = {
users: [],
user: {},
loading: false,
alert: null,
modal: {},
}
// get users from Search.js
searchUsers = async text => {
this.setState({ loading: true })
const res = await axios.get(
`https://api.github.com/search/users?q=${text}&client_id=${
process.env.REACT_APP_GITHUB_CLIENT_ID
}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);
this.setState({ users: res.data.items, loading: false })
console.log(text);
}
//get single profile
getUser = async username => {
this.setState({ loading: true })
const res = await axios.get(
`https://api.github.com/users/${username}?client_id=${
process.env.REACT_APP_GITHUB_CLIENT_ID
}&client_secret=${process.env.REACT_APP_GITHUB_CLIENT_SECRET}`);
this.setState({ user: res.data, loading: false });
this.setState({ modal: res.data, loadading: false });
}
//clear search
clearUsers = () => this.setState({ users: [], loading: false });
setAlert = (msg, type) => {
this.setState({ alert: { msg: msg, type: type } });
setTimeout(() => this.setState({ alert: null }), 5000);
};
render() {
return (
<Router>
<div className='App'>
<Navbar />
<div className="container">
<Alert alert={this.state.alert} />
<Switch>
<Route exact path='/'
render={props => (
<Fragment>
<Search
searchUsers={this.searchUsers}
clearUsers={this.clearUsers}
showClear={this.state.users.length > 0 ? true : false}
setAlert={this.setAlert}
/>
<Users loading={this.state.loading} users={this.state.users} />
</Fragment>
)} />
<Route path='/about' component={About} />
<Route path='/user/:login' render={props => (
<User {...props} getUser={this.getUser} user={this.state.user} loading={this.state.loading} />
)} />
<Route path='/modal/:login' render={props => (
<Modal {...props} getUser={this.getUser} modal={this.state.modal} loading={this.state.loading} />
)} />
</Switch>
</div>
</div>
</Router>
);
}
}
export default App;
here is my Modal.js
import React, { Fragment, Component } from 'react';
import ReactDom from 'react-dom';
import Spinner from '../layout/Spinner';
import { Link } from 'react-router-dom';
const modalRoot = document.getElementById('modal');
export default class Modal extends Component {
constructor() {
super();
this.el = document.createElement('div');
}
componentDidMount = () => {
modalRoot.appendChild(this.el);
};
componentWillUnmount = () => {
modalRoot.removeChild(this.el);
};
render() {
const {
children,
name,
avatar_url,
location,
bio,
blog,
followers,
following,
public_repos,
} = this.props.modal;
const { loading } = this.props;
if (loading) return <Spinner />
return (
ReactDom.createPortal(children, this.el)
)
}
}
any guide would be appriciated thanks in advance
You are passing the props already to Modal.
In Modal, do something like
Class Modal extends Component {
constructor(){
super(props);
}
render(){
const {
modal,
getUser,
loading,
anyOtherPropYouPassIn
} = this.props;
const { loading } = this.props;
if (loading) return <Spinner />
return (
ReactDom.createPortal(children, this.el)
)
}
I'm trying to pass the updated like count to the child component PostList.js.
it is called like
myLikes={post.Likes.length} // right here
The console.log(nextProps.myPosts)
makes a new likes object array, with the updated Likes count. How would i reflex this update to the UI ?
myLikes={post.Likes.length} gets Likes count, but does not get the updated nextProps.
Posts.js
import React, { Component } from 'react';
import PostList from './PostList';
import {connect} from 'react-redux';
import { withRouter, Redirect} from 'react-router-dom';
import {GetPosts} from '../actions/';
const Styles = {
myPaper:{
margin: '20px 0px',
padding:'20px'
}
,
wrapper:{
padding:'0px 60px'
}
}
class Posts extends Component {
state = {
posts: [],
loading: true,
isEditing: false,
// likes:[]
}
componentWillMount(){
this.props.GetPosts();
this.setState({
loading:false
})
}
componentWillReceiveProps(nextProps, prevState) {
let hasNewLike = true ;
if(prevState.posts && prevState.posts.length) {
for(let index=0; index < nextProps.myPosts.length; index++) {
if(nextProps.myPosts[index].Likes.length !==
prevState.posts[index].Likes.length) {
hasNewLike = true;
}
}
}
if(hasNewLike) {
this.setState({posts: nextProps.myPosts}); // here we are updating the posts state if redux state has updated value of likes
}
console.log(nextProps.myPosts)
// console.log(nextProps.myPosts[1].Likes.length) // shows a like count
}
render() {
const {loading} = this.state;
const { myPosts} = this.props
if (!this.props.isAuthenticated) {
return (<Redirect to='/signIn' />);
}
if(loading){
return "loading..."
}
return (
<div className="App" style={Styles.wrapper}>
<h1> Posts </h1>
<PostList posts={this.state.posts}/>
</div>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.user.isAuthenticated,
myPosts: state.post.posts,
})
const mapDispatchToProps = (dispatch, state) => ({
GetPosts: () => dispatch( GetPosts())
});
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Posts));
PostList.js
import React, { Component } from 'react';
import Paper from '#material-ui/core/Paper';
import Button from '#material-ui/core/Button';
import Typography from '#material-ui/core/Typography';
import moment from 'moment';
import {connect} from 'react-redux';
import {DeletePost, postLike, UpdatePost,EditChange, getCount, DisableButton} from '../actions/';
import PostItem from './PostItem';
import _ from 'lodash';
const Styles = {
myPaper: {
margin: '20px 0px',
padding: '20px'
}
}
class PostList extends Component{
constructor(props){
super(props);
this.state ={
title: '',
}
}
// Return a new function. Otherwise the DeletePost action will be dispatch each
// time the Component rerenders.
removePost = (id) => () => {
this.props.DeletePost(id);
}
onChange = (e) => {
e.preventDefault();
this.setState({
title: e.target.value
})
}
formEditing = (id) => ()=> {;
this.props.EditChange(id);
}
render(){
const {posts} = this.props;
// console.log(this.props.ourLikes);
return (
<div>
{posts.map(post => (
<Paper key={post.id} style={Styles.myPaper}>
<PostItem
myLikes={post.Likes.length} // right here
myTitle={this.state.title}
editChange={this.onChange}
editForm={this.formEditing}
isEditing={this.props.isEditingId === post.id}
removePost={this.removePost}
{...post}
/>
</Paper>
))}
</div>
);
}
}
const mapStateToProps = (state) => ({
isEditingId: state.post.isEditingId,
})
const mapDispatchToProps = (dispatch) => ({
// pass creds which can be called anything, but i just call it credentials but it should be called something more
// specific.
EditChange: (id) => dispatch(EditChange(id)),
UpdatePost: (creds) => dispatch(UpdatePost(creds)),
postLike: (id) => dispatch( postLike(id)),
// Pass id to the DeletePost functions.
DeletePost: (id) => dispatch(DeletePost(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(PostList);
Navbar.js
import React from 'react';
import {BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";
import signUp from '../auth/signUp';
import signIn from '../auth/signIn';
import Post from '../Post';
import Forgot from '../account/Forgot';
import Home from '../Home';
import Posts from '../Posts';
import Users from '../account/Users';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import Button from '#material-ui/core/Button';
import {withStyles} from '#material-ui/core';
import Dashboard from '../account/dashBoard';
import {connect} from 'react-redux';
import {createBrowserHistory} from 'history';
import PropTypes from 'prop-types';
import {compose} from 'redux';
import Axios from '../../Axios';
import updatePassword from '../account/updatePassword';
import ResetPassword from '../account/ResetPassword';
import ourStyles from '../../styles/ourStyles';
export const history = createBrowserHistory({forceRefresh: true});
const logout = (e) => {
e.preventDefault()
Axios.get(process.env.REACT_APP_LOGOUT, {withCredentials: true})
.then(res => {
// console.log(res);
if (res.status === 200) {
localStorage.removeItem('auth')
localStorage.removeItem('myAuth')
history.push('/')
}
})
.catch(err => {
// // their will be an inevitable error, so you would need this for it to work
localStorage.removeItem('auth')
localStorage.removeItem('myAuth')
history.push('/')
})
}
const Navbar = ({classes, isAuthenticated}) => (
<Router history={history}>
<div className={classes.navRoot}>
<AppBar position="static" className={classes.navbar}>
<Toolbar>
<Typography variant="h6" color="inherit">
Express Seqeuelize App
</Typography>
<Typography classcolor="inherit" className={classes.rightt}>
{!isAuthenticated && (
<Button>
<Link to="/" className={classes.rightToolbar}>
Home
</Link>
</Button>
)}
{isAuthenticated && (
<Button>
<Link className={classes.rightToolbar} to="/posts">
Posts
</Link>
</Button>
)}
{!isAuthenticated && (
<Button>
<Link to="/signUp" className={classes.rightToolbar}>
Sign Up
</Link>
</Button>
)}
{!isAuthenticated && (
<Button>
<Link to="/signIn" className={classes.rightToolbar}>
Sign In
</Link>
</Button>
)}
{isAuthenticated && (
<Button>
<Link className={classes.rightToolbar} to="/Post">
New Post
</Link>
</Button>
)}
{isAuthenticated && (
<Button>
<Link to="/dashboard" className={classes.rightToolbar}>
Dashboard
</Link>
</Button>
)}
{isAuthenticated && (
<Button onClick={logout}>
LogOut
</Button>
)}
</Typography>
</Toolbar>
</AppBar>
<Switch>
<Route exact path="/signUp" component={signUp}/>
<Route exact path="/" component={Home}/>
<Route exact path="/signIn" component={signIn}/>
<Route exact path="/Post" component={Post}/>
<Route exact path="/Posts" component={Posts}/>
<Route path="/Forgot" component={Forgot}/>
<Route path="/users" component={Users}/>
<Route exact path="/logout"/>
<Route exact path="/dashboard" component={Dashboard}/>
<Route path="/test"/>
<Route path="/reset/:token" component={ResetPassword}/>
<Route exact path="/updatePassword/:username" component={updatePassword}/>
</Switch>
</div>
</Router>
);
const mapStateToProps = (state) => ({
token: state.user.getToken, githubAuth: state.user.githubAuth,
// owl: state.user.owl,
isAuthenticated: state.user.isAuthenticated
})
const mapDispatchToProps = (dispatch) => ({
// logIn: (user) => dispatch(logIn(user))
});
Navbar.propTypes = {
isAuthenticatd: PropTypes.string
}
// export default withStyles(styles)(Navbar);
export default compose(connect(mapStateToProps, mapDispatchToProps), withStyles(ourStyles))(Navbar);
Reducer
const initialState = {
post: [],
postError: null,
posts:[],
isEditing:false,
isEditingId:null,
likes:[],
someLike:[],
postId:null
}
export default (state = initialState, action) => {
switch (action.type) {
case ADD_LIKE:
const newState = {...state}; // here I am trying to shallow copy the existing state;
const existingLikesOfPost = newState.posts.find(post => post.id == action.id).Likes;
newState.posts.find(post => post.id == action.id).Likes = [...existingLikesOfPost, action.newLikeObject];
console.log(newState)
return newState
console.log(newState)
{
"post": [],
"postError": null,
"posts": [
{
"id": 5,
"title": "React estiossssnsdd",
"post_content": "ssss",
"username": "owlman",
"createdAt": "2019-04-26T09:38:10.324Z",
"updatedAt": "2019-04-27T20:53:16.898Z",
"userId": 1,
"Likes": [
{
"id": 236,
"like": true,
"createdAt": "2019-04-27T20:57:44.395Z",
"updatedAt": "2019-04-27T20:57:44.395Z",
"userId": 1,
"postId": 5
},
{
"id": 220,
"like": true,
"createdAt": "2019-04-27T15:57:29.753Z",
"updatedAt": "2019-04-27T15:57:29.753Z",
"userId": 1,
"postId": 5
},
"isEditing": false,
"isEditingId": null,
"likes": [
117,
39
],
"someLike": [],
"postId": null
}
Post.js
componentWillReceiveProps(nextProps, prevState) {
let hasNewLike = true ;
if(prevState.posts && prevState.posts.length) {
for(let index=0; index < nextProps.myPosts.length; index++) {
if(nextProps.myPosts[index].Likes.length !==
prevState.posts[index].Likes.length) {
hasNewLike = true;
}
}
}
if(hasNewLike) {
this.setState({posts: nextProps.myPosts}); // here we are updating the posts state
if redux state has updated value of likes
}
console.log(nextProps.myPosts)
return true // return your change --- this can be a reason of not re-rendering
// console.log(nextProps.myPosts[1].Likes.length) // shows a like count
}
So it appears, that moving the PostList Component logic all to Posts.js seems to do the desired action. However it would be nice to keep the logic separated, but this logic will be good for now.
So componentWillReceiveProps needs to be on the component in which you want to make the update on. In this case i wanted to make the update on
post.Likes.length
which was on the PostList.js component. However, the componentWillReceiveProps is on the posts.js component. So i moved the logic on the Posts.js component.
Posts.js
import React, {Component} from 'react';
import PostList from './PostList';
import Paper from '#material-ui/core/Paper';
import {connect} from 'react-redux';
import {withRouter, Redirect} from 'react-router-dom';
import {
DeletePost,
postLike,
UpdatePost,
EditChange,
getCount,
DisableButton
} from '../actions/';
import PostItem from './PostItem';
import {GetPosts} from '../actions/';
const Styles = {
myPaper: {
margin: '20px 0px',
padding: '20px'
},
wrapper: {
padding: '0px 60px'
}
}
class Posts extends Component {
state = {
posts: [],
title: '',
loading: true,
isEditing: false,
}
componentWillMount() {
this.props.GetPosts();
}
removePost = (id) => () => {
this.props.DeletePost(id);
}
onChange = (e) => {
e.preventDefault();
this.setState({title: e.target.value})
}
formEditing = (id) => () => {
this.props.EditChange(id);
}
componentWillReceiveProps(nextProps, prevState) {
let hasNewLike = true;
if (prevState.posts && prevState.posts.length) {
for (let index = 0; index < nextProps.myPosts.length; index++) {
if (nextProps.myPosts[index].Likes.length !== prevState.posts[index].Likes.length) {
hasNewLike = true;
}
}
}
if (hasNewLike) {
this.setState({posts: nextProps.myPosts, loading: false}); // here we are updating the posts state if redux state has updated value of likes
}
}
render() {
const {loading} = this.state;
const {myPosts} = this.props
console.log(this.state.posts);
if (!this.props.isAuthenticated) {
return (<Redirect to='/signIn'/>);
}
if (loading) {
return "loading..."
}
return (
<div className="App" style={Styles.wrapper}>
<h1>Posts</h1>
{/* <PostList posts={this.state.posts}/> */}
<div>
{this.state.posts.map(post => (
<Paper key={post.id} style={Styles.myPaper}>
<PostItem myLikes={post.Likes.length} // right here
myTitle={this.state.title} editChange={this.onChange} editForm={this.formEditing} isEditing={this.props.isEditingId === post.id} removePost={this.removePost} {...post}/>
</Paper>
))}
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.user.isAuthenticated,
myPosts: state.post.posts, isEditingId:
state.post.isEditingId
})
const mapDispatchToProps = (dispatch, state) => ({
GetPosts: () => dispatch(GetPosts()),
// specific.
EditChange: (id) => dispatch(EditChange(id)),
UpdatePost: (creds) => dispatch(UpdatePost(creds)),
postLike: (id) => dispatch(postLike(id)),
// Pass id to the DeletePost functions.
DeletePost: (id) => dispatch(DeletePost(id))
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Posts));