React redux - useSelect() and useDispatch() when mapping objects - javascript

//state.buttons is an array - it is used to map buttons to a menu
function NavMenu() {
const buttons = useSelector((state) => state.buttons);
const dispatch = useDispatch();
const navButtons = buttons.map((button) => {
const checkDirection = (button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
};
checkDirection(button);
return (
<li key={button.id} >
<NavButton buttonData={button} />
</li>
);
});
return <ul>{navButtons}</ul>;
}
export default NavMenu;
//buttonSlice
const initialState = [
{
id: 'homeId',
prevPageNo: null,
pageNo: 1,
direction: 1,
firstAnimFrame: 1,
lastAnimFrame: 1,
},
{
id: 'aboutId',
prevPageNo: null,
pageNo: 2,
direction: 1,
firstAnimFrame: 1,
lastAnimFrame: 11,
},{...}
const buttonsSlice = createSlice({
name: 'ui',
initialState,
reducers: {
updateButtonsData: {
reducer(state, action) {
state = action.payload;
},
prepare(
id,
newPrevPageNo,
pageNo,
newDirection,
newFirstFrame,
newLastFrame
) {
return {
payload: {
id,
prevPageNo: newPrevPageNo,
pageNo,
direction: newDirection,
firstAnimFrame: newFirstFrame,
lastAnimFrame: newLastFrame,
};},},},},});
Hello, I have a navigation menu where several parameters must be dynamically updated within the UI when a user presses a button. Each button will behave differently depending on the previous button as pressed (order of pressed buttons matters). My solution is to compare the initial state of the nav buttons array to each subsequent remapping. I thought it would be good to store the history of the previously pressed button as a value inside the nav objects array. Each time the navigation is refreshed, new parameters are added and accessible as props inside the mapped button and can then be accessed onClick.
Currently, the dispatch function does not work with my code, and the mapped buttons array remains unchanged.

I assume that you are "triggering" the update data via checkDirection(button); and not onClick Event.
first this is a "no-go" code:
const navButtons = buttons.map((button) => {
const checkDirection = (button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
};
checkDirection(button);
return (
<li key={button.id} >
<NavButton buttonData={button} />
</li>
);
});
return <ul>{navButtons}</ul>;
}
If you want to trigger a function while rendering an element, put it inside useEffect and not "outside".
So, transfer that code inside NavButton like:
const checkDirection = useCallback(button) => {
if (button.pageNo >= button.prevPageNo) {
dispatch(updateButtonsData({ newDirection: 1 }));
} else {
dispatch(updateButtonsData({ newDirection: -1 }));
}
}, []);
useEffect(() => checkDirection(button), [checkDirection, button]);

Related

Ag-grid editable grid adding new row dynamically

I have an editable AgGrid in my functional component as below.
On the last column, I have buttons to Add/Remove rows.
Now I want the Add row to be displayed only for the last row. I am using cellRenderer for the last column.
With the below change, I get the Add button for the last row (i.e. on 2nd row in my case) on initial render. But if I click on Add for this 2nd row, while I get the Add button for the new 3rd row, but it does not get removed for the 2nd row. not sure if I am implementing this in the wrong way.
const MyCmp = (props) => {
const getData = () => {
return [{
id: 0,
firstName: 'F1',
lastName: 'L1'
}, {
id: 1,
firstName: 'F2',
lastName: 'L2',
}];
}
const [myCols, setMyCols] = useState(null);
const [gridData, setGridData] = useState(getData());
const [gridApi, setGridApi] = useState('');
let cellRules = {
'rag-red': params => {
if (params.data.lastName === 'INVALID_VAL') {
return true;
}
}
};
const handleGridReady = (params) => {
setGridApi(params.api);
setMyCols([{
headerName: 'F Name',
field: 'firstName',
editable: true
}, {
headerName: 'L Name',
field: 'lastName',
cellClassRules: cellRules,
editable: true
}, {
headerName: '',
field: 'buttonCol',
cellRenderer: 'customColRenderer',
cellRendererParams: {
addItems: addItems
}
}]
);
};
const createNewRowData = () => {
const newData = {
id: newCount,
firstName: '',
lastName: ''
};
newCount++;
return newData;
}
let newCount = getData().length;
const addItems = (addIndex, props) => {
const newItems = [createNewRowData()];
const res = props.api.applyTransaction({
add: newItems,
addIndex: addIndex,
});
setGridData(...gridData, res.add[0].data); // IS THIS CORRECT ?
if (props.api.getDisplayedRowCount() > props.api.paginationGetPageSize()) {
props.api.paginationGoToPage(parseInt((props.api.getDisplayedRowCount() / props.api.paginationGetPageSize())) + 1);
}
}
const onCellClicked = (e) => {
}
const frameworkComponents = () => {
return {customColRenderer: customColRenderer}
}
return (
<>
<MyAgGrid
id="myGrid"
columnDefs={myCols}
rowData={gridData}
frameworkComponents={{customColRenderer: customColRenderer}}
{...props}
/>
</>
)
}
My customColRenderer is as below;
export default (props) => {
let isLastRow = (props.rowIndex === (props.api.getDisplayedRowCount() -1)) ? true: false;
const addItems = (addIndex) => {
props.addItems(addIndex, props);
}
return (
<span>
{isLastRow ? <button onClick={() => addItems()}>Add</button> : null}
<span><button onClick={() => props.api.applyTransaction({remove: props.api.getSelectedRows()})}>Remove</button>
</span>
);
};
Within the AgGrid React internals a transaction is generated automatically when your rowData is updated, as such you can choose to apply the transaction either through the api, or by updating your state - you shouldn't need to do both (as you're currently doing). Generally with React I'd suggest updating the state to keep your state true to the data displayed in the grid, however that can depend on use case.
As for the further issue of your cell not updating - that'll be due to the fact AgGrid has detected no change in the 'value' of the cell, as it attempts to reduce the amount of unnecessary cell rendering done.
You could attempt to call:
api.refreshCells({ force: true });
After your api call applying the transaction (I'm not sure where this would need to happen using the setState approach).

Changing state from child

I have two components:
A parent component with a list of products
A child component a few levels deeper with a product
Child component should change the state in parent component with the help of passed callback from parent to child.
However, I get an error: Rendered more hooks than during the previous render
Code:
// Parent
const ProductsListScreen = () => {
const [localData, setLocalData] = React.useState([
{ id: 1, count: 1 }
]);
const onProductChecked = ({ id, count }) => {
const checkedItemIndex = localData.findIndex((item) => item.id === id);
const checkedItem = checkedItemIndex ? localData[checkedItemIndex] : null;
if (checkedItem) {
// If the input count is equal to item's count in state - set checked to true
if (checkedItem.count == count) {
// Set parent state of checked product to checked true
setLocalTaskItems((prevState) => [
...prevState.slice(0, checkedItemIndex),
{
...prevState[checkedItemIndex],
countIsGood: true,
},
...prevState.slice(idx + 1),
]);
}
}
};
// List of products
return <ProductsList onProductChecked={onProductChecked} />;
};
// Child a few levels deeper - Product
const onContinuePress = (params, callback) => {
// onProductChecked callback
callback(params);
};
const Product = ({ onProductChecked }) => {
const id = 1;
const count = 1;
return (
<Button
onPress={() =>
onContinuePress(
{
id,
count,
},
onProductChecked
)
}
>
Submit
</Button>
);
};
Send localData and setLocalData as props to the child and do onProductChecked in there with props.localData and props.setLocalData
like this
<ProductsList localData={localData} setLocalData={setLocalData} />;

How to hide a specific element inside .map function in React?

I am looking for a way to hide a div once the button thats in it is clicked and continue to show all other div's.
I've tried using the setState method, however when setting it to false with onClick() all of my objects disappear.
class App extends React.PureComponent {
state: {
notHidden: false,
}
constructor(props: any) {
super(props);
this.state = {search: '', notHidden: true};
this.hideObject = this.hideObject.bind(this)
}
hideThisDiv() {
this.setState({notHidden: false})
}
async componentDidMount() {
this.setState({
objects: await api.getObjects()
});
}
render = (objects: Object[]) => {
return ({Object.map((object) =>
<div key={index} className='class'>
<button className='hide' type='button' onClick={() => hideThisDiv()}>Hide</button>
<p>object.text</p>
</div>}
render() {
const {objects} = this.state;
return (<main>
<h1>Objects List</h1>
<header>
<input type="search" onChange={(e) => this.onSearch(e.target.value)}/>
</header>
{objects ? this.render(objects) : null}
</main>)
}
);
The data is a data.json file filled with many of these objects in the array
{
"uuid": "dsfgkj24-sfg34-1r134ef"
"text": "Some Text"
}
Edit: Sorry for the badly asked question, I am new to react.
Not tested, just a blueprint... is it what you want to do?
And yes I didn't hide, I removed but again, just an idea on how you can hide button separately, by keeping in state which ones are concerned.
function MagicList() {
const [hidden, hiddenSet] = useState([]);
const items = [{ id:1, text:'hello'}, { id:2, text:'from'}, { id:3, text:'the other sided'}]
const hideMe = id => hiddenSet([...hidden, id]);
return {
items.filter( item => {
return hidden.indexOf(item.id) !== -1;
})
.map( item => (
<button key={item.id} onClick={hideMe.bind(this, item.id)}>{item.text}</button>
))
};
}
Edition
const hideMe = id => hiddenSet([...hidden, id]);
It is just a fancy way to write:
function hideMe(id) {
const newArray = hidden.concat(id);
hiddenSet(newArray);
}
I suggest using a Set, Map, or object, to track the element ids you want hidden upon click of button. This provides O(1) lookups for what needs to be hidden. Be sure to render your actual text and not a string literal, i.e. <p>{object.text}</p> versus <p>object.text</p>.
class MyComponent extends React.PureComponent {
state = {
hidden: {}, // <-- store ids to hide
objects: [],
search: "",
};
// Curried function to take id and return click handler function
hideThisDiv = id => () => {
this.setState(prevState => ({
hidden: {
...prevState.hidden, // <-- copy existing hidden state
[id]: id // <-- add new id
}
}));
}
...
render() {
const { hidden, objects } = this.state;
return (
<main>
...
{objects
.filter((el) => !hidden[el.uuid]) // <-- check id if not hidden
.map(({ uuid, text }) => (
<div key={uuid}>
<button
type="button"
onClick={this.hideThisDiv(uuid)} // <-- attach handler
>
Hide
</button>
<p>{text}</p>
</div>
))}
</main>
);
}
}

How to keep every two identical names red if both were clicked consecutively?

I have list items represent names, when clicking any name it turns red then take one second to return black again, but clicking two identical names consecutively make them keep red color, not turning black again
you can imagine it as a memory game, but i tried to make a simple example here of what i am trying to achieve in the original project
This is my code and my wrong trial:
const App = () => {
const { useState } = React;
const items = [
{
name: 'mark',
id: 1,
red: false
},
{
name: 'peter',
id: 2,
red: false
},
{
name: 'john',
id: 3,
red: false
},
{
name: 'mark',
id: 4,
red: false,
},
{
name: 'peter',
id: 5,
red: false
},
{
name: 'john',
id: 6,
red: false
}
];
const [names, setNames] = useState(items);
const [firstName, setFirstName] = useState(null);
const [secondName, setSecondName] = useState(null)
const handleItemClick = (item) => {
setNames(prev => prev.map(i => i.id === item.id ? { ...i, red: true } : i));
//the problem is here
setTimeout(() => {
setNames(prev => prev.map(n => {
if (secondName && (secondName.name === firstName.name) && n.name === firstName.name) {
return { ...n,red: true }
}
return { ...n, red: false };
}))
}, 1000)
if (!firstName) setFirstName(item);
else if (firstName && !secondName) setSecondName(item)
else if (firstName && secondName) {
setFirstName(item);
setSecondName(null)
}
}
return (
<div class="app">
<ul class="items">
{
names.map(i => {
return (
<Item
item={i}
handleItemClick={handleItemClick}
/>
)
})
}
</ul>
</div>
)
}
const Item = ({ item, ...props }) => {
const { id, name, red } = item;
const { handleItemClick } = props;
return (
<li
className={`${red ? 'red' : ''}`}
onClick={() => handleItemClick(item)}
>
{name}
</li>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
But this code doesn't work correctly, when clicking two identical names consecutively they don't keep red color and turning black again
To me it seems the issue is overloading the event handler and violating the Single Responsibility Principle.
The handler should be responsible for handling the click event and nothing else. In this case, when the element is clicked you want to add the id to the state of selected/picked names, and toggle the red state value of item with matching id. Factor the timeout effect into (strangely enough) an useEffect hook, with the picks as dependencies. This inverts the logic of the timeout to clearing/resetting the state versus setting what is "red" or not. You can/should also move any logic of determining matches into this same effect (since it already has the dependencies anyway).
useEffect(() => {
... logic to determine matches
const timer = setTimeout(() => {
// time expired, reset only if two names selected
if (firstName && secondName) {
setFirstName(null);
setSecondName(null);
setNames(names => names.map(name => ({ ...name, red: false })));
}
}, 1000);
// clean up old timeout when state updates, i.e. new selected
return () => clearTimeout(timer);
}, [firstName, secondName]);
This will allow you to simplify your name setting logic to
if (!firstName) {
setFirstName(item);
} else {
setSecondName(item);
}
Note: I believe you need another data structure to hold/track/store existing matches made by the user.
How this works:
Starting from clean state, no names are chosen
When first name is picked, firstName is null and updated, red state updated
Timeout is set (but won't clear state yet)
When second name is picked, firstName is defined, so secondName is updated, red state updated
If match, add match to state (to keep red)
Timeout expire and reset state (go back to step 1)
The following is how I'd try to simplify state a bit more, using an array of selected ids that only update if the selected id isn't already chosen and 2 picks haven't been chosen yet.
const App = () => {
const [names, setNames] = useState(items);
const [picks, setPicks] = useState([]);
const [matched, setMatched] = useState({});
/**
* On click event, add id to `picks` array, allow only two picks
*/
const onClickHandler = id => () =>
picks.length !== 2 &&
!picks.includes(id) &&
setPicks(picks => [...picks, id]);
/**
* Effect to toggle red state if id is included in current picks
*/
useEffect(() => {
setNames(names =>
names.map(name => ({
...name,
red: picks.includes(name.id)
}))
);
}, [picks]);
/**
* Effect checks for name match, if a match is found it is added to the
* `matched` array.
*/
useEffect(() => {
// matches example: { mark: 1, peter: 0, john: 0 }
const matches = names.reduce((matches, { name, red }) => {
if (!matches[name]) matches[name] = 0;
red && matches[name]++;
return matches;
}, {});
const match = Object.entries(matches).find(([_, count]) => count === 2);
if (match) {
const [matchedName] = match;
setMatched(matched => ({ ...matched, [matchedName]: matchedName }));
}
const timer = setTimeout(() => {
if (picks.length === 2) {
setPicks([]);
setNames(names => names.map(name => ({ ...name, red: false })));
}
}, 1000);
return () => clearTimeout(timer);
}, [names, picks]);
return (
<div className="App">
<ul>
{names.map(item => (
<Item
key={item.id}
item={item}
matches={matched}
onClick={onClickHandler(item.id)}
/>
))}
</ul>
</div>
);
};
const Item = ({ item, matches, ...props }) => {
const { name, red } = item;
return (
<li
className={classnames({
red: red || matches[name], // for red text color
matched: matches[name] // any other style to make matches stand out
})}
{...props}
>
{name}
</li>
);
};

How to prevent a double click in ReactJS

I am working on search filter in ReactJS and I face a problem. Problem is about when User does some search and wants to click on next (because I have pagination in app) then the User will click twice to load other pages of data.
I need to avoid this behaviour: I mean when user does single click on next it should be "load a data" instead of "double click".
I am new to ReactJS, please expert help me
Code
btnClick() {
const { Item,skip , filtered, data } = this.state
if(filtered.length>0 || !data.length ){
window.alert("Hello,")
this.setState({
filtered:[],
skip:0
},()=>this.getData());
return false
}else {
window.alert("Hello , Dear")
this.setState(
{
Item,
skip: skip + pageSize
},
() => this.getData()
);}
}
You can have a isLoading state and set the disabled prop on the button when in this state which will not allow the button to be clicked again while the data is being fetched.
btnClick() {
const {
Item,
skip,
filtered,
data
} = this.state;
if (filtered.length > 0 || !data.length) {
window.alert("Hello,")
this.setState({
filtered: [],
skip: 0
}, () => this.fetchData());
return false
} else {
window.alert("Hello , Dear")
this.setState({
Item,
skip: skip + pageSize
},
() => this.fetchData()
);
}
}
fetchData() = async() => {
this.setState({ isLoading: true });
await this.getData();
this.setState({ isLoading: false });
}
render() {
const {
isLoading
} = this.state;
const buttonProps = isLoading ? { disabled: true} ? {};
return (
<button onClick={this.btnClick} { ...buttonProps }>
Click to fetch
</button>
);
}

Categories

Resources