Refresh parent view / mapStateToProps when dialog closes - javascript

I have created a dialog that opens up on each row in a table, I can edit and send within that dialog info about a person. I close the dialog and need to refresh the page before I see it updated. What I need to do is update the parent component on dialog close.
I have put together a fluff free version of my parent component and how I am calling the data below -
import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import PeopleEditDialog from './PeopleEditDialog';
class EnhancedTable extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
openPeopleEditDialog: false
};
this.handlePeopleEditDialog = this.handlePeopleEditDialog.bind(this);
}
handlePeopleEditDialog() {
this.setState({
openPeopleEditDialog: !this.state.openPeopleEditDialog
});
render() {
const { openPeopleEditDialog } = this.state;
const { loader, people, peopleListError } = this.props;
return (
<React.Fragment>
<Toolbar>
<div className="actions">
<Tooltip title="Edit">
<IconButton aria-label="Edit" onClick={this.handlePeopleEditDialog}>
<Edit />
</IconButton>
</Tooltip>
<PeopleEditDialog
open={this.state.openPeopleEditDialog}
onClose={this.handlePeopleEditDialog}
selected={selectedDialog}
/>
</div>
</Toolbar>
<div className="flex-auto">
<div className="table-responsive-material">
<Table>
<TableBody>
//Rows of people data
{people}
</TableBody>
</Table>
</div>
</div>
</React.Fragment>
)
);
}
}
const mapStateToProps = ({ peopleList }) => {
const { loader, people, peopleListError, appliedFilters } = peopleList;
return { loader, people, peopleListError, appliedFilters};
}
export default withRouter(connect(mapStateToProps, {})(withStyles(styles, { withTheme: true })(EnhancedTable)));
peopleList does not update unless I refresh. I need to apply something to get the latest when I close the dialog:
<PeopleEditDialog
open={this.state.openPeopleEditDialog}
onClose={this.handlePeopleEditDialog}
selected={selectedDialog}
/>
So how do I call the latest from mapStateToProps when the component closes so I get a refreshed list?

Related

How do I make it so only a specific modal appears when I press a button in React?

Currently trying to make modals in React and want to make a grid where "button 1" shows "modal 1" and "button 2" shows "modal 2" etc.
At the moment when I press my button to show a modal it shows both modal 1 and modal 2. How do I set it up so button 1 only opens modal 1?
This is my App.js:
import React from 'react';
import './main.css';
import Modal from './components/Modal/modal';
class App extends React.Component {
state = {
show: false
};
showModal = x => {
this.setState({
show: !this.state.show
});
};
render() {
return (
<div>
<div className="button-container">
<button className="toggle-button" onClick={x => {
this.showModal(x);
}}>Show yourself Modal!</button>
</div>
<Modal onClose={this.showModal} show={this.state.show} title="Test modal 1" id="1">Lorem ipsum</Modal>
<Modal onClose={this.showModal} show={this.state.show} title="Test modal 2" id="2">I am a different modal</Modal>
</div>
);
}
}
export default App;
And this is my modal.js component:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './modal.css';
export default class Modal extends Component {
onClose = x => {
this.props.onClose && this.props.onClose(x);
};
render() {
if(!this.props.show) {
return null;
}
return (
<div className="modal-wrapper">
<h2 className="modal-header">{this.props.title}</h2>
<div>{this.props.children}</div>
<div>
<button className="modal-close" onClick={this.onClose}></button>
</div>
</div>
)
}
}
Modal.propTypes = {
onClose: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired
};
The simplest way would be to add a second key to your state so that you have a way to manage showing both modals independently.
class App extends React.Component {
state = {
show1: false,
show2: false
};
Then make your change function to be a curried function that accepts a parameter to update the correct part of state. In order to use a variable to access an object key, we need to access it as an array like this:
showModal = (modal) => (e) => {
this.setState({
[modal]: !this.state[modal]
});
};
Then use it like this:
render() {
return (
<div>
<div className="button-container">
<button className="toggle-button" onClick={this.showModal('show1')}>Show yourself Modal 1!</button>
<button className="toggle-button" onClick={this.showModal('show2')}>Show yourself Modal 2!</button>
</div>
<Modal onClose={this.showModal('show1')} show={this.state.show1} title="Test modal 1" id="1">Lorem ipsum</Modal>
<Modal onClose={this.showModal('show2')} show={this.state.show2} title="Test modal 2" id="2">I am a different modal</Modal>
</div>
);
}
}
At the moment you have nothing in your state to tell which modal to show. You're using this.state.show to control the visibility of both modals.
You could introduce a state property in your App component which is used to choose which modal to show. For example, passing in a modalId or similar to your click handler. (disclaimer: untested syntax, but the principal is right!)
So your state may look like this:
state = {
[
{
id: 1,
show: false
},
{
id: 2,
show: false
},
]
}
Then, in your click handler, you'd need to pass in the id of the modal to show / hide. You'd need to determine this from something in your UI.
showModal(id) => {
this.setState({
[id]: !this.state[id].show
})
}
If you require Button for every Modal and control its behaviour with it then you can introduce a state to the modal component itself by doing something like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './modal.css';
export default class Modal extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
}
}
toggleShow = () => {
const { showModal } = this.state;
this.setState({showModal: !showModal})
};
render() {
const { showModal } = this.state;
return (
<div className="modal-wrapper">
{ showModal &&
<div>
<h2 className="modal-header">{this.props.title}</h2>
<div>{this.props.children}</div>
</div>
}
<div>
<button className="modal-close" onClick={() => this.toggleShow()}>{this.props.btnText}</button>
</div>
</div>
)
}
}
It can be build further to alter the default behaviour. This should clean your App.js code.

React - Add user to list of Favorites

I have a simple user list with several details from the following api: https://gorest.co.in/public-api/users, where I want to add a selected user to a list of favorites. I am working with react-router to navigate between pages. Is this possible with React or do I also need Redux?
I have a complete LIVE EXAMPLE here with the user page and favorites.
Here is the code below for the user list:
import React from "react";
import axios from "axios";
import NavLinks from "./components/navLink";
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [],
addToFav: false
};
this.list = [];
}
componentDidMount() {
this.getList();
}
/* get users list */
getList = async () => {
const api =
"https://gorest.co.in/public-api/users?_format=json&access-token=3qIi1MDfD-GXqOSwEHHLH73Y3UitdaFKyVm_";
await axios
.get(api)
.then(response => {
this.list = response.data.result;
this.setState({
list: this.list
});
})
.catch(err => {
console.log(err);
});
};
addToFav = () => {
this.setState(
{
addToFav: !this.state.addToFav
},
() => console.log(this.state.addToFav)
);
};
render() {
let style = {
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(250px, 1fr))",
padding: "1rem",
gridGap: "1rem 1rem"
};
return (
<div>
<NavLinks />
<ul style={style}>
{this.state.list.map(user => {
return (
<li key={user.id}>
<div>
<img className="thumb" alt="" src={user._links.avatar.href} />
</div>
<div className="userInfo">
<p>
{user.first_name} {user.last_name}
</p>
</div>
<button onClick={this.addToFav}>Add to Favorites</button>
</li>
);
})}
</ul>
</div>
);
}
}
Thank you!
Here's a working codesandbox: https://codesandbox.io/s/brave-fire-4kd4p
This train of thought pretty much follows what #Chris G mentioned. Have a top-level state that holds the list of users and the favorites list. Then pass those as props to the individual components.
App.js
Hit your API here instead of inside your UserList component to prevent any unnecessary re-renders.
import React, { Component } from "react";
import UserList from "./userList";
import FavoriteList from "./favoriteList";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import axios from "axios";
export default class App extends Component {
state = {
list: [],
favorites: []
};
addFavorite = favorite => {
const { favorites } = this.state;
if (!favorites.some(alreadyFavorite => alreadyFavorite.id == favorite.id)) {
this.setState({
favorites: [...this.state.favorites, favorite]
});
}
};
getList = async () => {
const api =
"https://gorest.co.in/public-api/users?_format=json&access-token=3qIi1MDfD-GXqOSwEHHLH73Y3UitdaFKyVm_";
await axios
.get(api)
.then(response => {
this.setState({
list: response.data.result
});
})
.catch(err => {
console.log(err);
});
};
componentDidMount() {
this.getList();
}
render() {
return (
<Router>
<Switch>
<Route
path="/"
exact
render={() => (
<UserList list={this.state.list} addFavorite={this.addFavorite} />
)}
/>
<Route
path="/favorites"
render={() => <FavoriteList favorites={this.state.favorites} />}
/>
</Switch>
</Router>
);
}
}
UserList.js
Call the addFavorite event-handler on button-click to pass that item back up to the parent-state.
import React from "react";
import NavLinks from "./components/navLink";
export default class UserList extends React.Component {
render() {
let style = {
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(250px, 1fr))",
padding: "1rem",
gridGap: "1rem 1rem"
};
return (
<div>
<NavLinks />
<ul style={style}>
{this.props.list.map(user => {
return (
<li key={user.id}>
<div>
<img className="thumb" alt="" src={user._links.avatar.href} />
</div>
<div className="userInfo">
<p>
{user.first_name} {user.last_name}
</p>
</div>
<button onClick={() => this.props.addFavorite(user)}>
Add to Favorites
</button>
</li>
);
})}
</ul>
</div>
);
}
}
Favorite.js
Use the favorites array that was passed in as a prop and iterate over it.
import React from "react";
import NavLinks from "./components/navLink";
export default class FavoriteList extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { favorites } = this.props;
return (
<div>
<NavLinks />
<ul>
{favorites.map(user => {
return (
<li key={user.id}>
<div>
<img className="thumb" alt="" src={user._links.avatar.href} />
</div>
<div className="userInfo">
<p>
{user.first_name} {user.last_name}
</p>
</div>
</li>
);
})}
</ul>
</div>
);
}
}
Is this possible with React or do I also need Redux?
Most if not all of those problems can be solved without redux just by using component state. It just gets increasingly difficult to pass the state to the components needing it the more global state you have and the more components at different depth need to access and update it.
In your case it might be sufficient to store the favorites in a component state high up the tree and pass it to the components consuming it. You could either pass it directly to the components or you could use react context to make it accessible to components deep in the tree.
A simple example:
const FavoritesContext = React.createContext({favorites: []});
const FavoritesProvider = ({children}) => {
const [favorites, setFavorites] = useState([]);
const add = useCallback(favorite => setFavorites(current => [...current, favorite]), [setFavorites]);
return (
<FavoritesContext.Provider value={{favorites, add}}>
{children}
</FavoritesContext.Provider>
};
You can use it like that:
<FavoritesProvider>
<MyApp />
</FavoritesProvider>
then anywhere in a component in your app:
const MyComponent = () => {
const {favorites, add} = useContext(FavoritesContext);
const [draft, setDraft] = useState('');
const handleChange = event => setDraft(event.target.value);
const handleAdd = () => {
add(draft);
setDraft('');
};
return (
<div>
<ul>
{favorites.map(favorite => <li>{favorite}</li>)}
</ul>
<input value={draft} type="text" onChange={handleChange} />
<button onClick={handleAdd}>Add</button>
</div>
);
}
In this simple example the favorites are just text but they could as well be objects. Also it demonstrates how you could provide a handler for adding a favorite. You could implement e.g. a handler for removing favorites in the same way.
Persisting your favorites is yet another topic you may need to deal with. You could use e.g. localStorage for that or you could store that in a database on a server and fetch it when your app mounts the first time.
I have changed your file a bit take a look - https://codesandbox.io/s/clever-butterfly-vb2iz
One way is to use the localstorage of browser.
But this way is slighty expensive and synchronous.
Update the list whenever the favorited item status is changed via
localStorage.setItem('users',JSON.stringify(users));
And look for the favorited items via
localStorage.getItem('users');//You need to parse this by JSON.parse()
Maintain a isFavorite variable in the object list.
let users=[{name:"Mr.A",isFavorite:false},{name:"Mr.B",isFavorite:true},...];
On the click of favoriting button this.addToFav change it as follows
addToFav=user=>{
const {users}=this.state;
this.setState({
users:users.map(userObject=>userObject.id===user.id?
{...userObject,isFavorite:!userObject.isFavorite}:user)
},()=>{saveToLocal(this.state.users)});
}
Now you can access the favorite items even if the page is reloaded and stays there till you clear the storage.Use this localStorage.clear() for that.
First I would change your onClick to this:
<button onClick={() => this.addToFav(user.id)}>Add to Favorites</button>
This will allow you to pass the id to the addToFave function.
Then I would add a new state called faves (an array) and every time someone clicks the add button I would add their id into this array. This will allow you to filter your original list when you want to display the faves.
this.state = {
list: [],
faves: [],
};
}
addToFav = (id) => {
this.setState(prevState => ({
faves: [...prevState.faves, id],
}));
};
When I want to use the list of faves instead of the normal list I would do this:
const favesList = [];
this.state.list.map(listItem =>
this.state.faves.find(
faveId => listItem.id === faveId
) && favesList.push(item);
Then I would pass that to the faves component
I changed accordingly, please try
https://codesandbox.io/s/youthful-poincare-7oeh0
the key is you can use push state to your link like below
<Link to={{ pathname: "/favorites", state: { favList: this.props.favList }}} onClick={() => this.forceUpdate()}>
later on under your fav page call to retrieve the state
this.props.location.state.favList
i have changed the code a little by using react context.
I would not use redux for this cause i think it would be a overkill.
Anyways here is the updated sandbox...
Link for sandbox

Passing a variable between non-nested components using Context API

Suppose I have two components which aren't nested: a button and a panel. When the button is clicked, the panel will show or hide depending on the previous state (like an on/off switch). They aren't nested components, so the structure looks like this:
<div>
<Toolbar>
<Button />
</Toolbar>
<Content>
...
<ButtonPanel />
</Content>
</div>
I can't change the structure of the DOM. I also can't modify any other component other than the button and panel components.
The Button and ButtonPanel components are related, however, and will be used together throughout the solution. I need to pass a property to the panel to let it know when to show or when to hide. I was thinking about doing it with Context API, but I think there's something I'm doing wrong and the property never updates.
This is my code:
Context
import React from 'react';
export const ButtonContext = React.createContext({
showPanel: false,
});
Button
import React, { Component } from 'react';
import { ButtonContext } from './ButtonContext';
class Button extends Component {
constructor() {
super();
this.state = {
showPanel: false,
};
}
render() {
return (
<ButtonContext.Provider value={{ showPanel: this.state.showPanel }}>
<li>
<a
onClick={() => this.setState({ showPanel: !this.state.showPanel }, () => console.log('Changed'))}
>
<span>Button</span>
</a>
</li>
</ButtonContext.Provider>
);
}
}
export { Button };
Panel
import React, { Component } from 'react';
import { Panel, ListGroup, ListGroupItem } from 'react-bootstrap';
import { ButtonContext } from './ButtonContext';
class ButtonPanel extends Component {
static contextType = ButtonContext;
render() {
return (
<ButtonContext.Consumer>
{
({ showPanel }) => {
if (showPanel) {
return (
<Panel id="tasksPanel">
<Panel.Heading >Panel Heading</Panel.Heading>
<ListGroup>
<ListGroupItem>No Items.</ListGroupItem>
</ListGroup>
</Panel>
);
}
return null;
}
}
</ButtonContext.Consumer>
);
}
}
export { ButtonPanel };
I've also tried simply accessing the context in the ButtonPanel component like so:
render() {
const context = this.context;
return context.showPanel ?
(
<Panel id="tasksPanel">
<Panel.Heading >Tasks</Panel.Heading>
<ListGroup>
<ListGroupItem className="tasks-empty-state">No tasks available.</ListGroupItem>
</ListGroup>
</Panel>
)
:
null;
}
What am I doing wrong?
Thanks
From the React docs:
Accepts a value prop to be passed to consuming components that are descendants of this Provider.
So this means that <ButtonContext.Provider> has to wrap <ButtonContext.Consumer> or it has to be higher up in the component hierarchy.
So based on your use case, you could do:
// This app component is the div that wraps both Toolbar and Content. You can name it as you want
class App extends Component {
state = {
showPanel: false,
}
handleTogglePanel = () => this.setState(prevState => ({ togglePanel: !prevState.togglePanel }));
render() {
return (
<ButtonContext.Provider value={{ showPanel: this.state.showPanel, handleTogglePanel: this.handleTogglePanel }}>
<Toolbar>
<Button />
</Toolbar>
<Content>
<ButtonPanel />
</Content>
</ButtonContext.Provider>
);
}
}
class Button extends Component {
...
<ButtonContext.Consumer>
{({ handleTogglePanel }) => <a onClick={handleTogglePanel} />}
</ButtonContext.Consumer>
}
class ButtonPanel extends Component {
...
<ButtonContext.Consumer>
{({ showPanel }) => showPanel && <Panel>...</Panel>}
</ButtonContext.Consumer>
}

React Component receive props but doesn't render it, why?

I have a page displaying user's books.
On this MyBooks page, React component mount. When it's mounted it fetch user's books through API. Then it update component's state with user's books.
mount component
fetch books through API
when we have results, update component's state
render again BooksList component (but it's not happening)
Here is my code for MyBooks component :
class MyBooks extends Component {
// TODO: fetch user info
constructor(props) {
super(props);
this.state = {
books: [],
errors: []
};
this.fetchBooks = this.fetchBooks.bind(this);
}
componentDidMount() {
console.log('component mounted!');
this.fetchBooks();
}
fetchBooks() {
let _this = this;
BooksLibraryApi.getBooks().then(foundBooks => {
console.log('books found:', foundBooks);
_this.setState({
books: foundBooks
});
});
}
render() {
console.log('MyBooks state:', this.state);
return (
<Section>
<Container>
<h1>My books</h1>
<BooksList books={this.state.books} />
</Container>
</Section>
);
}
}
export default withRouter(MyBooks);
Here is the result for console.log('books found:', foundBooks):
Here is my code for BooksList component :
class BooksList extends React.Component {
render() {
console.log('BooksList props:', this.props);
return (
<Columns breakpoint="mobile">
{this.props.books.map((book, i) => {
console.log(book);
return (
<Columns.Column
key={i}
mobile={{ size: 'half' }}
desktop={{ size: 2 }}
>
<BookCard book={book} />
</Columns.Column>
);
})}
</Columns>
);
}
}
export default BooksList;
Here is the code for BookCard component:
class BookCard extends React.Component {
constructor(props) {
super(props);
console.log('props', props);
this.readBook = this.readBook.bind(this);
this.addBook = this.addBook.bind(this);
this.deleteBook = this.deleteBook.bind(this);
this.wantBook = this.wantBook.bind(this);
}
readBook() {
BooksLibraryApi.readBook(this.props.book.id);
}
addBook() {
BooksLibraryApi.addBook(this.props.book.id);
}
wantBook() {
BooksLibraryApi.wantBook(this.props.book.id);
}
deleteBook(e) {
BooksLibraryApi.deleteBook(this.props.book.id, e);
}
render() {
return (
<div className="card-book">
<Link to={`/book/${this.props.book.id}`}>
{this.props.book.doHaveThumbnail ? (
<Image
alt="Cover"
src={this.props.book.thumbnailUrl}
size={'2by3'}
/>
) : (
<div className="placeholder">
<span>{this.props.book.title}</span>
</div>
)}
</Link>
<Button fullwidth color="primary" size="small" onClick={this.wantBook}>
Add to wishlist
</Button>
</div>
);
}
}
export default withRouter(BookCard);
The console.log in BooksList component is not called. Which means that the component is render only one time, when the this.props.books array is empty.
I don't understand why BooksList is not rendered again when his props are updated (when MyBooks component has his state updated).
Strange behavior: I'm using React Router, and when I first click on the link "My books" (which go to my MyBooks component), it doesn't work, but when I click again on it, everything works fine. Which means that something is wrong with rendering / component's lifecyles.
Thanks.

React-Redux -- selecting item from list

New to React, I am having hard time selecting an item from a recipe list. I am working on how to delete a recipe from the list, but first I want to figure out how to select that particular recipe.
Here's an example of a well-working demo:
https://www.freecodecamp.com/challenges/build-a-recipe-box
As you can see, each item has its own Delete button and I have done in my code as well.
I have the following code in my container:
src/containers/recipebox.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListGroup, ListGroupItem, Panel, Button, Modals } from 'react-bootstrap'
import { bindActionCreators } from 'redux';
import { deleteRecipe } from '../actions/index';
class RecipeBox extends Component {
constructor(props){
super(props);
this.state = {
open: false
};
this.renderRecipeList = this.renderRecipeList.bind(this)
}
renderRecipeList(recipeItem,index){
const recipe = recipeItem.recipe;
const ingredients = recipeItem.ingredients;
return(
<div key={index}>
<Panel bsStyle="primary" collapsible header={<h3>{recipe}</h3>}>
<ListGroup >
<ListGroupItem header="Ingredients"></ListGroupItem>
{ingredients.map(function(ingredient,index){
return <ListGroupItem key={index}>{ingredient}</ListGroupItem>;
})}
<ListGroupItem>
<Button
onClick={this.props.deleteRecipe}
value={recipeItem}
bsStyle="danger">Delete
</Button>
<Button
onClick={() => console.log('EDIT!')}
bsStyle="info">Edit
</Button>
</ListGroupItem>
</ListGroup>
</Panel>
</div>
)
}
render(){
return(
<div className="container">
<div className='panel-group'>
{this.props.addRecipe.map(this.renderRecipeList)}
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
addRecipe : state.addRecipe
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({deleteRecipe : deleteRecipe}, dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(RecipeBox);
Where my Action is as so:
src/actions/index.js
export const RECIPE_ADD = 'RECIPE_ADD';
export const RECIPE_EDIT = 'RECIPE_EDIT';
export const RECIPE_DELETE = 'RECIPE_DELETE';
export function addRecipe(recipe) {
return {
type: RECIPE_ADD,
payload: recipe
}
}
export function editRecipe(recipe) {
return {
type: RECIPE_EDIT,
payload: recipe
}
}
export function deleteRecipe(event) {
return {
type: RECIPE_DELETE,
payload: event.target.value
}
}
Specifically I am looking at this in my container:
<Button
onClick={this.props.deleteRecipe}
value={recipeItem}
bsStyle="danger">Delete
</Button>
In my reducer, I am seeing as
payload: "[object Object]"
How do I use onClick event listener that will select the appropriate recipe from the list?
(note: I haven't implemented the reducer yet, I just want to see how I can see the action.payload to be the selected recipe)
EDIT:
I found the solution. Simply I needed to figure out how to pass an argument using onClick without invoking by itself.
The following ES6 code did the trick:
<Button
onClick={() => this.props.deleteRecipe(recipeItem)}
bsStyle="danger">Delete
</Button>
Cheers
I found the solution. Simply I needed to figure out how to pass an argument using onClick without invoking by itself. The following ES6 code did the trick:
<Button
onClick={() => this.props.deleteRecipe(recipeItem)}
bsStyle="danger">Delete
</Button

Categories

Resources