getting state from connect(mapStateToProps) > UNDEFINED - javascript

I am kind of struggling to get the state of book, when I log the props I get book: undefined.
Any tips?
import React from 'react';
import { connect } from 'react-redux';
import BookForm from './BookForm';
const EditBook = (props) => {
console.log(props)
return (
<div>
hello
</div>
);
};
const mapStateToProps = (state, props) => {
return {
book: state.books.find((book) => book.id === props.match.params.id)
};
};
export default connect(mapStateToProps)(EditBook);
Rest of the project is on my Github: https://github.com/bananafreak/bookshelf

Update the Link in the BookListItem. You don't need the : before ${id}. The : is causing the problem.
<Link to={`/edit/${id}`}><h2>{title}</h2></Link>
In the EditBook component return the following
<BookForm {...props}></BookForm>
In the BookForm constructor set the state from props.book
this.state = { ...props.book }

I've ran into issues with this before where === will fail because the types of book.id and props.match.params.id are different. The params values are always strings - maybe try parseInt(props.match.params.id) or == comparison (with type coercion).

I managed to found where was my mistake.
In the component BookListItem:
import React from 'react';
import { Link } from 'react-router-dom';
const BookListItem = ({ author, title, genre, text, id, pages }) => (
<div>
<Link to={`/edit/${id}`}><h2>{title}</h2></Link>
<h3>by: {author}</h3>
<p>{genre}</p>
{pages > 0 && <p>{pages} pages</p>}
<p>{text}</p>
<p>-------------------------------</p>
</div>
);
export default BookListItem;
Before the ${id} I had unfortunately colon {/edit/:${id}} so then book.id and props.match.params.id could not match

Related

Importing React Autosuggest as Functional Component from Another JSX File

I'm currently making a simple web frontend with react using react-autosuggest to search a specified user from a list. I want to try and use the Autosuggest to give suggestion when the user's type in the query in the search field; the suggestion will be based on username of github profiles taken from github user API.
What I want to do is to separate the AutoSuggest.jsx and then import it into Main.jsx then render the Main.jsx in App.js, however it keeps giving me 'TypeError: _ref2 is undefined' and always refer to my onChange function of AutoSuggest.jsx as the problem.
Below is my App.js code:
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Header from './views/header/Header';
import Main from './views/main/Main';
import Footer from './views/footer/Footer';
const App = () => {
return (
<>
<Header/>
<Main/> <- the autosuggest is imported in here
<Footer/>
</>
);
}
export default App;
Below is my Main.jsx code:
import React, { useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import axios from 'axios';
import { useEffect } from 'react';
import AutoSuggest from '../../components/AutoSuggest';
const Main = () => {
const [userList, setUserList] = useState([]);
useEffect(() => {
axios.get('https://api.github.com/users?per_page=100')
.then((res) => setUserList(res.data))
.catch((err) => console.log(err));
}, [])
return (
<Container>
<br/>
<Row>
<AutoSuggest userList={userList} placeHolderText={'wow'} />
</Row>
</Container>
);
}
export default Main;
Below is my AutoSuggest.jsx code:
import React, { useState } from "react";
import Autosuggest from 'react-autosuggest';
function escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getSuggestions(value, userList) {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return userList.filter(user => regex.test(user.login));
}
function getSuggestionValue(suggestion) {
return suggestion.name;
}
function renderSuggestion(suggestion) {
return (
<span>{suggestion.name}</span>
);
}
const AutoSuggest = ({userList, placeHolderText}) => {
const [value, setValue] = useState('');
const [suggestions, setSuggestions] = useState([]);
const onChange = (event, { newValue, method }) => { <- error from console always refer here, I'm not quite sure how to handle it..
setValue(newValue);
};
const onSuggestionsFetchRequested = ({ value }) => {
setValue(getSuggestions(value, userList))
};
const onSuggestionsClearRequested = () => {
setSuggestions([]);
};
const inputProps = {
placeholder: placeHolderText,
value,
onChange: () => onChange()
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={() => onSuggestionsFetchRequested()}
onSuggestionsClearRequested={() => onSuggestionsClearRequested()}
getSuggestionValue={() => getSuggestionValue()}
renderSuggestion={() => renderSuggestion()}
inputProps={inputProps} />
);
}
export default AutoSuggest;
The error on browser (Firefox) console:
I have no idea what does the error mean or how it happened and therefore unable to do any workaround.. I also want to ask if what I do here is already considered a good practice or not and maybe some inputs on what I can improve as well to make my code cleaner and web faster. Any input is highly appreciated, thank you in advance!
you have to write it like this... do not use the arrow function in inputProps
onChange: onChange

Minified React error #31 with sharepoint online using React + redux

I'm facing an error that has been searching by myself for 2 days. But currently It's still not resolved, so I came here to ask If anyone ever faced this?
I'm using Redux toolkit in a sharepoint online project for passing data to each other components.
The first component worked perfectly, but when I use useSelector function for the 2nd one, this error appears
Although when I tried using console.log for each component, both are still receiving the data but
using data for the 2nd component will happen this error.
So has anyone ever faced this please help me out~, here is my codes
slice:
import { createSlice } from '#reduxjs/toolkit';
export interface titleState {
title: string;
}
const initialState: titleState = {
title : 'Your title'
};
export const titleSlice = createSlice({
name: 'title',
initialState,
reducers: {
SET_TITLE: (state, action) => {
state.title = action.payload;
}
}
});
export const { SET_TITLE } = titleSlice.actions;
export default titleSlice.reducer;
store
import { configureStore } from '#reduxjs/toolkit';
import titleReducer from "../features/titleSlice/titleSlice";
export const store: any = configureStore({
reducer: {
title: titleReducer
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
first component:
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const FirstComponent: FunctionComponent<FirstComponent> = (
props
) => {
const STATE_TITLE = useSelector((state: RootState) => state.title);
console.log(STATE_TITLE);
const dispatch = useDispatch<AppDispatch>();
const handleTitle = (e) => {
dispatch(SET_TITLE(e.target.value));
setTitle(e.target.value);
}
return (
<div>
<textarea
onChange={handleTitle} //works fine
/>
</div>
}
second component:
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const SecondComponent: FunctionComponent<ISecondComponentProps> = (props) => {
const TITLE_STATE = useSelector((state: RootState) => state.title)
console.log(TITLE_STATE)
return (
<div>
{YOUR_TITLE} //this line happens error
</div>
)
and here is the error from development tab :
The error happens because your TITLE_STATE is an object and not a string. Try changing the return statement of the second component to
<div>
{TITLE_STATE?.title}
</div>
If this works, the error was because you were trying to render objects directly. And investigate why your textarea component returns an object instead of string as value, since that is the root cause here

How to give a new REDUIX item a unique ID? [duplicate]

This question already has answers here:
How do I create a GUID / UUID?
(70 answers)
Closed 12 months ago.
I am mapping an array of data with props into a component. Then onClick I pull some of that data into redux/reducer from the rendered items, trying to render the same data - but in a different spot on the page.
My problem is (I assume?) that the ID's are the same - I render data with keys's/id's that were already taken - while React wants unique ones.
I am not sure, if that's what's causing the problem - but I keep getting a warning that react wants unique key props.
(it's a shop app - on click, i want to add the chosen item to a cart with redux... )
Thoughts?
here I am building the component to render
import { useDispatch, useSelector } from 'react-redux'
import { add } from '../features/addToCart'
export const ReduxshopProps = (props) => {
const dispatch = useDispatch()
const handleAddToCart = (props) => {
dispatch(add(props));
};
return (<>
<div key={props.id} className='shopitem'>
<img src={props.url} />
<h2>{props.title}</h2>
<p className='boldprice'>${props.price}</p>
<button onClick={() => handleAddToCart(props) }
>
ADD TO CART
</button>
</div>
</>
)
}
here I am passing data into the component
import React from "react"
import { ReduxshopProps } from "./ReduxshopProps"
import shopdata from "./shopdata"
export default function ReduxShop() {
const cards = shopdata.map(props => {
return (
<ReduxshopProps
key={props.id}
title={props.title}
price={props.price}
url={props.url}
/>
)
})
return (
<div className='shopwrapper'>
<h1>TradingView Indicators</h1>
<div className='itemWrapper'>
{cards}
</div>
</div>
)
}
here's the REDUX code that pulls data from above
import { createSlice } from "#reduxjs/toolkit";
const initialState = {
cartItems: [],
cartTotalQuantity: 0,
cartTotalAmount: 0,
}
export const addToCartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
add(state, action ) {
const itemIndex = state.cartItems.findIndex(
(item) => item.id === action.payload.id
);
if(itemIndex >= 0){
state.cartItems[itemIndex].cartQuantity += 1
} else {
const tempProduct = {...action.payload, cartQuantity: 1}
state.cartItems.push(tempProduct);
}
},
},
});
export const {add} = addToCartSlice.actions;
export default addToCartSlice.reducer;
and here I'm trying to render the data when someone clicks on a button.. onClick it acts as all components have the same ID - also I'm getting the key prop error from here, below
import React from 'react'
import { useSelector } from 'react-redux'
function Cart() {
const cart = useSelector((state) => state.cart)
return (
<div>
<h1>Cart</h1>
{cart.cartItems.map(cartItem => (
<div key={cartItem.id}>
<p>product : {cartItem.title}</p>
<p>price {cartItem.price}</p>
<p>quantity : {cartItem.cartQuantity}</p>
<p>url : <img src={cartItem.url} /></p>
</div>
))}
</div>
)
}
export default Cart
What you are trying to do is, assign UUID
First in terminal:
npm install uuid
Then:
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
More on here, a sof thread: How to create a GUID / UUID
The library, on npm: https://www.npmjs.com/package/uuid

I'm getting Not a Number value in my React app

Can't render the noofcartItems in my react UI. I get only NaN value as output in my UI.
Anything wrong in the syntax ? The context I created also seems to be failing.
Please ignore the console logs as I used it for debug purposes.
import CartContext from '../../CartStore/cart-context.js';
import CartIcon from '../Cart/CartIcon.js';
import './CartButton.css';
import { useContext } from 'react';
const CartButton = (props) => {
const context = useContext(CartContext);
const noofcartItems = context.items.reduce((curNo, item) => {
console.log(curNo, item.amount,curNo + item.amount, 'curNo + item.amount');
return curNo + item.amount;
}, 0);
console.log(noofcartItems,'No of cart items');
return (<button className='button' onClick={props.onClick}>
<span className='icon'>
<CartIcon/>
</span>
<span>Cart</span>
<span className='badge'>{noofcartItems}</span>
</button>
)
};
export default CartButton;
import React from 'react'
const CartContext = React.createContext({
items:[],
totalAmount: 0,
addItem: (item) => {},
removeItem: (id) => {}
});
export default CartContext;
You should console log your context.items array and check for the values of amount variable. It seems that one of the amount values must be undefined.

React Redux - passing arguments to event handler not working

Ok, I got a head scratcher I need a little bit of help with. The setup is that I have React/Redux app with a Categories page that reads a list of categories from an API, then lists them out. That part works fine. What I'm trying to do is pass in an event handler to each of the category child components that, when clicked, dispatches an action that toggles the state of the component, i.e., if the category is selected and clicked on, it will "unselect" it (which actually means deleting an entry from a database table called user_category), and if not selected, will "select" that category for that user (add an entry in the user_category table).
So I've got an onclick handler (handleCatClick) that is supposed to ultimately pass a categoryId and a userId to perform these operations. Unfortunately what I'm finding that even though these arguments are being passed to the function, they end up being undefined. So I'm not sure if I'm passing this function correctly or what exactly I've missed.
Everything works other than this - maybe you can help me spot the problem ;-)
Click here to view the database layout
Click here to see how the category page looks
The applicable pages in my app:
The architecture looks basically like this:
/views/[Categories]
- index.js (wrapper for the Categories Component)
- CategoriesComponent.jsx (should be self-explanatory)
[duck]
- index.js (just imports a couple of files & ties stuff together)
- operations.js (where my handleCatClick() method is)
- types.js (Redux constants)
- actions.js (Redux actions)
- reducers.js (Redux reducers)
[components]
[Category]
- index.jsx (the individual Category component)
/views/index.js(main Category page wrapper)
import { connect } from 'react-redux';
import CategoriesComponent from './CategoriesComponent';
import { categoriesOperations } from './duck'; // operations.js
const mapStateToProps = state => {
// current state properties passed down to LoginComponent (LoginComponent.js)
const { categoryArray } = state.categories;
return { categoryArray }
};
const mapDispatchToProps = (dispatch) => {
// all passed in from LoginOperations (operations.js)
const loadUserCategories = () => dispatch(categoriesOperations.loadUserCategories());
const handleCatClick = () => dispatch(categoriesOperations.handleCatClick());
return {
loadUserCategories,
handleCatClick
}
};
const CategoriesContainer = connect(mapStateToProps,mapDispatchToProps)(CategoriesComponent);
export default CategoriesContainer;
/views/CategoriesComponent.jsx (display layer for the Categories view)
import React from 'react';
import {Row,Col,Container, Form, Button} from 'react-bootstrap';
import {Link} from 'react-router-dom';
import './styles.scss';
import Category from './components/Category';
import shortid from 'shortid';
class CategoriesComponent extends React.Component {
constructor(props) {
super(props);
this.loadUserCats = this.props.loadUserCategories;
this.handleCatClick = this.props.handleCatClick;
}
componentWillMount() {
this.loadUserCats();
}
render() {
return (
<Container fluid className="categories nopadding">
<Row>
<Col xs={12}>
<div className="page-container">
<div className="title-container">
<h4>Pick your favorite categories to contine</h4>
</div>
<div className="content-container">
<div className="category-container">
{
this.props.categoryArray.map((item) => {
return <Category className="category" handleClick={this.props.handleCatClick} key={shortid.generate()} categoryData={item} />
})
}
</div>
</div>
</div>
</Col>
</Row>
</Container>
)
}
}
export default CategoriesComponent
/views/Categories/components/index.jsx (Single Category Component)
import React from 'react';
import {Row,Col,Container, Form, Button} from 'react-bootstrap';
import './styles.scss';
import Img from 'react-image';
class Category extends React.Component {
constructor(props) {
super(props);
this.state = {
categoryName: this.props.categoryData.category_name,
categoryImg: this.props.categoryData.category_img,
categoryId: this.props.categoryData.category_id,
userId: this.props.categoryData.user_id,
selected: this.props.categoryData.user_id !== null,
hoverState: ''
}
this.hover = this.hover.bind(this);
this.hoverOff = this.hoverOff.bind(this);
this.toggleCat = this.toggleCat.bind(this);
}
toggleCat() {
// the onClick handler that is supposed to
// pass categoryId and userId. When I do a
// console.log(categoryId, userId) these two values
// show up no problem...
const {categoryId, userId} = this.state;
this.props.handleClick(categoryId, userId);
}
hover() {
this.setState({
hoverState: 'hover-on'
});
}
hoverOff() {
this.setState({
hoverState: ''
});
}
render() {
const isSelected = (baseCat) => {
if(this.state.selected) {
return baseCat + " selected";
}
return baseCat;
}
return (
<div className={"category" + ' ' + this.state.hoverState} onClick={this.toggleCat} onMouseOver={this.hover} onMouseOut={this.hoverOff}>
<div className={this.state.selected ? "category-img selected" : "category-img"}>
<Img src={"/public/images/category/" + this.state.categoryImg} className="img-fluid" />
</div>
<div className="category-title">
<h5 className={this.state.selected ? "bg-primary" : "bg-secondary"}>{this.state.categoryName}</h5>
</div>
</div>
);
}
}
export default Category;
/views/Categories/duck/operations.js (where I tie it all together)
// operations.js
import fetch from 'cross-fetch';
import Actions from './actions';
import Config from '../../../../config';
const loadCategories = Actions.loadCats;
const selectCat = Actions.selectCat;
const unSelectCat = Actions.unSelectCat;
const localState = JSON.parse(localStorage.getItem('state'));
const userId = localState != null ? localState.userSession.userId : -1;
const loadUserCategories = () => {
return dispatch => {
return fetch(Config.API_ROOT + 'usercategories/' + userId)
.then(response => response.json())
.then(json => {
dispatch(loadCategories(json));
});
}
}
const handleCatClick = (categoryId, categoryUserId) => {
// HERE IS WHERE I'M HAVING A PROBLEM:
// for whatever reason, categoryId and categoryUserId
// are undefined here even though I'm passing in the
// values in the Category component (see 'toggleCat' method)
var params = {
method: categoryUserId !== null ? 'delete' : 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(
{
"category_id": categoryId,
user_id: categoryUserId !== null ? categoryUserId : userId
}
)
};
const toDispatch = categoryUserId !== null ? unSelectCat : selectCat;
return dispatch => {
return fetch(Config.API_ROOT + 'usercategories/', params)
.then(response => response.json())
.then(json => {
dispatch(toDispatch(json));
});
}
}
export default {
loadUserCategories,
handleCatClick
}
The problem that I am having:
So I'm thinking I'm either not referencing handleCatClick correctly, or I'm somehow not passing the categoryId and userId correctly so that when it finally gets to handleCatClick(categoryId, categoryUserId) in operations.js, it ends up as undefined. It's probably something simple but I can't spot it. NOTE: I haven't included files like the types.js or reducers.js, because they seem to be outside the scope of the problem, but if you need them please let me know. Thanks in advance for your help!
Try this changes: Add params to these handlers
const handleCatClick = (categoryId, categoryUserId) => dispatch(categoriesOperations.handleCatClick(categoryId, categoryUserId));
and
return <Category className="category" handleClick={(categoryId, categoryUserId) => this.props.handleCatClick(categoryId, categoryUserId)} key={shortid.generate()} categoryData={item} />

Categories