Dispatch Toggle in Redux without saving it in State? - javascript

How I do it right now
I have a list of items. Right now, when the user presses button X, shouldShowItem is toggled. shouldShowItem ultimately lies in redux and is passed down into Item as a prop. it's either true or false. When it changes, toggleDisplay is called and changes state in my hook:
useEffect(() => {
toggleDisplay(!display); //this is just a useState hook call
}, [shouldShowItem]); //PS: I'm aware that I don't need this extra step here, but my actual code is a bit more complicated, so I just simplified it here.
My Problem is, that I have one single shouldShowItem property in redux, not one shouldShowItem for each item. I don't want to move this property into the redux-state for each and every item.
Problem:
The problem with my construction however is that shouldShowItem is being saved, which means that if I toggle it at time X for item Y, and then my Item Z also re-renders as a result of an unrelated event, it will re-render with an updated shouldShowItem state, - although that state change was intended for Item X.
Essentially, I am saving the state of shouldShowItem in redux while I just need a toggle, that I can dispatch once, that works on the current Item, and then isn't read / needed anymore. I want to basically dispatch a toggle, - I don't care about the state of each item within redux, I just care that it's toggled once.
Suggestions?
Edit: More Code
Item:
const Item = ({shouldShowItem, itemText, updateCurrentItem})=>
{
const [display, toggleDisplay] = useState(false);
useEffect(() => {
if (isSelected) {
toggleDisplay(!display);
}
}, [shouldShowItem]);
return (
<div
onClick={() => {
toggleDisplay(!display);
updateCurrentItem(item._id);
}}
>
{display && <span>{itemText}</span>}
</div>
);
}
Mapping through item list:
allItems.map((item, i) => {
return (
<Item
key={i}
shouldShowItem={this.props.shouldShowItem}
itemText={item.text}
updateCurrentItem={this.props.updateCurrentItem}
);
});
The props here come from redux, so shouldShowItem is a boolean value that lies in redux, and updateCurrentItem is an action creator. And well, in redux i simply just toggle the shouldShowItem true & false whenever the toggle action is dispatched. (The toggle action that sets & unsets true/false of shouldShowItem is in some other component and works fine)

instead of a boolean shouldShowItem, why not convert it into an object of ids with boolean values:
const [showItem, setShowItem] = useState({id_1: false, id_2: false})
const toggleDisplay = id => {
setShowItem({...showItem, [id]: !showItem[id]})
updateCurrentItem(id)
}
allItems.map((item, i) => {
return (
<Item
key={i}
shouldShowItem={showItem[item._id]}
itemText={item.text}
updateCurrentItem={toggleDisplay}
);
});
const Item = ({shouldShowItem, itemText, updateCurrentItem}) => {
return (
<div
onClick={() => toggleDisplay(item._id)}
>
{shouldShowItem && <span>{itemText}</span>}
</div>
)
}

Related

How to stop making api call on re-rendering in React?

In my homepage, I have code something like this
{selectedTab===0 && <XList allItemList={some_list/>}
{selectedTab===1 && <YList allItemList={some_list2/>}
Now, In XList, I have something like this:
{props.allItemList.map(item => <XItem item={item}/>)}
Now, Inside XItem, I am calling an api to get the image of XItem.
Now my problem is When In homepage, I switched the tab from 0 to 1 or 1 to 0, It is calling all the API's in XItem again. Whenever I switched tab it calls api again. I don't want that. I already used useEffect inside XItem with [] array as second parameter.
I have my backend code where I made an api to get the image of XItem. The API is returning the image directly and not the url, so I can't call all api once.
I need some solution so that I can minimize api call.
Thanks for help.
The basic issue is that with the way you select the selected tab you are mounting and unmounting the components. Remounting the components necessarily re-runs any mounting useEffect callbacks that make network requests and stores any results in local component state. Unmounting the component necessarily disposes the component state.
{selectedTab === 0 && <XList allItemList={some_list} />}
{selectedTab === 1 && <YList allItemList={some_list2} />}
One solution could be to pass an isActive prop to both XList and YList and set the value based on the selectedTab value. Each component conditionally renders its content based on the isActive prop. The idea being to keep the components mounted so they only fetch the data once when they initially mounted.
<XList allItemList={some_list} isActive={selectedTab === 0} />
<YList allItemList={some_list2} isActive={selectedTab === 1} />
Example XList
const XList = ({ allItemList, isActive }) => {
useEffect(() => {
// expensive network call
}, []);
return isActive
? props.allItemList.map(item => <XItem item={item}/>)
: null;
};
Alternative means include lifting the API requests and state to the parent component and passing down as props. Or using a React context to do the same and provide out the state via the context. Or implement/add to a global state management like Redux/Thunks.
Just to quickly expand on Drew Reese's answer, consider having your tabs be children of a Tabs-component. That way, your components are (slightly) more decoupled.
const MyTabulator = ({ children }) => {
const kids = React.useMemo(() => React.Children.toArray(children), [children]);
const [state, setState] = React.useState(0);
return (
<div>
{kids.map((k, i) => (
<button key={k.props.name} onClick={() => setState(i)}>
{k.props.name}
</button>
))}
{kids.map((k, i) =>
React.cloneElement(k, {
key: k.props.name,
isActive: i === state
})
)}
</div>
);
};
and a wrapper to handle the isActive prop
const Tab = ({ isActive, children }) => <div hidden={!isActive}>{children}</div>
Then render them like this
<MyTabulator>
<Tab name="x list"><XList allItemList={some_list} /></Tab>
<Tab name="y list"><YList allItemList={some_list2} /></Tab>
</MyTabulator>
My take on this issue. You can wrap XItem component with React.memo:
const XItem = (props) => {
...
}
const areEqual = (prevProps, nextProps) => {
/*
Add your logic here to check if you want to rerender XItem
return true if you don't want rerender
return false if you want a rerender
*/
}
export default React.memo(XItem, areEqual);
The logic is the same if you choose to use useMemo.
If you want to use useCallback (my default choice) would require only to wrap the call you make to the api.

The question about React.memo and performance optimisation

Suppose I have long list (let's assume there is no pagination yet) where each list item has input and ability to update own value (as a part of collection). Let's say code looks something like that:
const initItems = [
{ id: 0, label: "Hello world" },
...
{ id: 100, label: "Goodby" }
];
function List() {
const [items, setItems] = React.useState([...initItems]);
const handleChange = React.useCallback((e, id) => {
setItems(items.map(item => {
if (item.id === id) {
return {
...item,
label: e.target.value
}
}
return item;
}));
}, [items]);
return (
<ul>
{items.map(({ id, label }) => {
return (
<Item
id={id}
key={id}
label={label}
onChange={handleChange}
/>
)
})}
</ul>
)
}
// Where Item component is:
const Item = React.memo(({ onChange, label, id }) => {
console.log('Item render');
return (
<li>
<input type="text" value={label} onChange={e => onChange(e, id)} />
</li>
)
});
Looks pretty straightforward, right? While wrapping Item component with React.memo() what I wanted to achieve is to avoid re-render of each Item when some of the Item's gets updated. Well, I'm not sure it should works with this strategy, since each Item is a part of collection (items) and when I update any Item then items gets mapped and updated. What I did try - is to write custom areEqual method for Item component, where I do comparison of label value from props:
function areEqual(prev, next) {
return prev.label === next.label;
}
however with this approach the behaviour of updating items breaks down completely and updating next item reset previous updates and so on (I even could not observe any pattern to explain).
So the question: is it possible to avoid re-rendering of every item in such collection while having ability to update value of individual item?
Your problem here that you change callback on each render. So, you change callback, it changes onChange and this, in turn, runs rerender. To avoid it you can use updater function with setState.
const handleChange = React.useCallback((e, id) => {
// I made separate function so it would be easier to read
// You can just write `(items) =>` before your `items.map` and it will work
function updater(items) {
// we have freshest items here
return items.map((item) => {
if (item.id === id) {
return {
...item,
label: e.target.value,
};
}
return item;
});
}
// pass function
setItems(upadter);
// removed items from dependencies
}, []);
This way, your updater function will always get current value of state into parameters, and your props will update for actually updated item. Another solution would be to write custom updater that compares all values, but onChange. This is ok in short term, but this can become complex and cumbersome to maintain.
Here is live example: https://codesandbox.io/s/unruffled-johnson-ubz1l

How to set checked/unchecked functionality on Html table in Reactjs

I have an array of Json objects('filteredUsers' in below code) and I'm mapping them to a html table. Json object would look like {id: xyz, name: Dubov}
The below code would display a html table with a single column or basically a list. Each row will have name of user and a grey checkbox(unchecked) next to it initially. I want to select users in the table and when I select or click on any item in table, the checkmark has to turn green(checked).
<table className="table table-sm">
{this.state.filteredUsers && (
<tbody>
{this.state.filteredUsers.map((user) => (
<tr key={user.id}>
<td onClick={() => this.selectUser(user)}>
<span>{user.name}</span> //Name
<div className={user.selected? "checked-icon": "unchecked-icon"}> //Checkmark icon
<span class="checkmark"> </span>
</div>
</td>
</tr>
))}
</tbody>
)}
</table>
I tried setting a 'selected' key to each object. Initially object doesn't have 'selected' key so it will be false(all unchecked). I set onClick method for 'td' row which sets 'selected' key to object and sets it to true. Below function is called onClick of td or table item.
selectUser = (user) => {
user.selected = !user.selected;
};
Now the issue is this will only work if I re-render the page after every onClick of 'td' or table item. And I'm forced to do an empty setState or this.forcedUpdate() in selectUser method to trigger a re-render. I read in multiple answers that a forced re-render is bad.
Any suggestions or help would be highly appreciated. Even a complete change of logic is also fine. My end goal is if I select an item, the grey checkmark has to turn green(checked) and if I click on it again it should turn grey(unchecked). Similarly for all items. Leave the CSS part to me, but help me with the logic. Thanks.
How about something like this:
const Users = () => {
const [users, setUsers] = useState([])
useEffect(() => {
// Fetch users from the API when the component mounts
api.getUsers().then((users) => {
// Add a `selected` field to each user and store them in state
setUsers(users.map((user) => ({ ...user, selected: true })))
})
}, [])
const toggleUserSelected = (id) => {
setUsers((oldUsers) =>
oldUsers.map((user) =>
user.id === id ? { ...user, selected: !user.selected } : user
)
)
}
return (
<ul>
{users.map((user) => (
<li key={user.id} onClick={() => toggleUserSelected(user.id)}>
<span>{user.name}</span>
<div className={user.selected ? "checked-icon" : "unchecked-icon"}>
<span class="checkmark" />
</div>
</li>
))}
</ul>
)
}
I've used hooks for this but the principles are the same.
This looks to be a state issue. When updating data in your react component, you'll need to make sure it's happening in one of two ways:
The data is updated by a component higher up in the tree and then is passed to this component via props.
this will cause your component to re-render with the new props and data, updating the "checked" property in your HTML.
In your case, it looks like you're using this second way:
The data is stored in component state. Then, when you need to update the data, you'd do something like the below.
const targetUser = this.state.filteredUsers.find(user => user.id === targetId)
const updatedUser = { ...targetUser, selected: !targetUser.selected }
this.setState({ filteredUsers: [ ...this.state.filteredUsers, updatedUser ] })
Updating your state in this way will trigger an update to your component. Directly modifying the state object without using setState does not trigger the update.
Please keep in mind that, when updating objects in component state, you'll need to pass a new, full object to setState in order to trigger the update. Something like this will not work: this.setState({ filteredUsers[1].selected: false });
Relevant documentation

Don't understand how to update React hook

I've tried to ask this ungooglable to me question dozens of times. I've made almost the simpliest example possible to ask this question now.
I change the value of the hook in the handleChange method. But then console.log always shows previous value, not new one. Why is that?
I need to change the value of the hook and then instead of doing console.log use it to do something else. But I can't because the hook always has not what I just tried to put into it.
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
console.log(value);
};
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
}
You can try it here.
https://codesandbox.io/s/awesome-lumiere-y2dww?file=/src/App.js
I believe the problem is that you are logging the value in the handleChange function. Console logging the value outside of the function logs the correct value. Link: https://codesandbox.io/s/async-fast-6y71b
Hooks do not instantly update the value you want to update, as you might have expected with classes (though that wasn't guaranteed either)
State hook, when calling setValue will trigger a re-render. In that new render, the state will have the new value as you expected. That's why your console.log sees the old value.
Think of it as in each render, the state values are just local variables of that component function call. And think as the result of your render as a result of your state + props in that render call. Whenever any of those two changes (the props from your parent component; the state, from your setXXX function), a new render is triggered.
If you move out the console.log outside of the callback handler (that is, in the body of your rendered), there you will see in the render that happens after your interaction that the state is logged correctly.
In that sense, in your callbacks events from interactions, you just should worry about updating your state properly, and the next render will take care to, given the new props/state, re-render the result
The value doesn't "change" synchronously - it's even declared with a const, so even the concept of it changing inside the same scope doesn't make sense.
When changing state with hooks, the new value is seen when the component is rerendered. So, to log and do stuff with the "new value", examine it in the main body of the function:
const ControllableStates = () => {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
};
// ADD LOG HERE:
console.log('New or updated value:', value);
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
</div>
);
}
You're printing out the old value in handleChange, not the new val.
i.e.
const handleChange = val => {
setValue(val);
console.log(value);
};
Should be:
const handleChange = val => {
setValue(val);
console.log(val);
};
Actually, lets get a little back and see the logic behind this scenario.
You should use the "handleChange" function ONLY to update the state hook, and let something else do the logic depends on that state hook value, which is mostly accomplished using "useEffect" hook.
You could refactor your code to look like this:
const handleChange = val => {
setValue(val);
};
React.useEffect(() => {
console.log(value);
// do your logic here
}, [value])
So I think that the main problem is that you're not understanding how React
deals with components and states.
So, I'll vastly simplify what React does.
React renders a new component and remembers it's state, it's inputs (aka
props) and it's the state and inputs of the children.
If at any given point an input changes or a state changes, React will render
the component again by calling the component function.
Consider this:
function SomeComponent(text) {
return (<div>The <i>text</i> prop has the value {text}</div>)
}
Let's say the initial prop value is "abc", React will call SomeComponent("abc"), then the function returns
<div>The <i>text</i> prop has the value abc</div> and React will render that.
If the prop text does not change, then React does nothing anymore.
Now the parent component changes the prop to "def", now React will call
SomeComponent("def") and it will return
<div>The <i>text</i> prop has the value def</div>, this is different from
last call, so React will update the DOM to reflect the change.
Now let's introduce state
function SomeComponent() {
const [name, setName] = React.useState("John")
function doSomething()
{
alert("The name is " + name)
}
return (
<p>Current name: {name}</p>
<button onClick={() => setName("Mary")}>Set name to Mary</button>
<button onClick={() => setName("James")}>Set name to James</button>
<button onClick={() => doSomething()}>Show current name</button>
)
}
So here React will call SomeComponent() and render the name John and the 3
button. Note that the value of the name variable does not change during the
current execution, because it's declared as const. This variable only reflects
the latest value of the state.
When you press the first button, setName() is executed. React will internally store
the new value for the state and because of the change of state, it will render
the component again, so SomeComponent() will be called once again. Now the variable name will
reflect again the latest value of the state (that's what useStatedoes), so in this case Mary. React
will realize that the DOM has to be updated and it prints the name Mary.
If you press the third button, it will call doSomething() which will print the
latest value of the name variable because every time React calls
SomeComponent(), the doSomething() function is created again with the latest
value of name. So once you've called setName(), you don't need to do
anything special to get the new value. React will take care of calling the
component function again.
So when you don't use class components but function components, you have to think
differently: the function gets called all the time by React and at any single
execution it reflects the latest state at that particular point in time. So when you
call the setter of a useState hook, you know that the component function will
be called again and useState will return the new value.
I recommend that you read this article, also read again Components and
Props from the React documentation.
So how should you do proceed? Well, like this:
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const handleChange = val => {
setValue(val);
console.log(value);
};
const handleClick = () => {
// DOING SOMETHING WITH value
alter(`Now I'm going to do send ${value}`);
}
return (
<div>
<div>{value}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
handleChange(newValue);
}}
options={options}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
/>
<button type="button" onClick={handleClick}>Send selected option</button>
</div>
);
}
See CodeSandbox.

componentWillReceiveProps() duplicates the elements from map

componentWillReceiveProps = (newProps) => {
console.log("data ");
let apiData = newProps.apiData;
if (apiData.topProfiles && apiData.topProfiles.success) {
let therapists = apiData.topProfiles.therapists
let hasMore = true
if (!therapists.length) {
hasMore = false
}
this.setState(() => ({
therapists: this.state.therapists.concat(therapists),
hasMore: hasMore,
pageLoading: false
}))
} else if (apiData.therapistsByName && apiData.therapistsByName.success) {
let therapists = apiData.therapistsByName.therapists,
resTitle = therapists.length ?
`Results for "${this.state.searchName}"`
: `Looks like there are no results for "${this.state.searchName}"`
this.setState(() => ({
therapists: therapists,
hasMore: false,
pageLoading: false,
resultsTitle: resTitle
}))
}
I read about componentWillReceiveProps and is not safe anymore. How can I implement it much more efficient.
I have a function which render a list of therapists, but if I am in therapist pages where the content is rendered, and click on "Specialists" (button path) again in Header, the therapist list duplicates.
renderTherapists = () => {
console.log("this state therapists: ", this.state.therapists)
let items = this.state.therapists.map( (t, idx) => (
<TherapistCard therapist={t} key={idx} />
))
return (
<div ref={0} className="therapist-list">
{ items }
</div>
)
}
console log after header button press
The code you have keeps concatenating therapists to the therapists array on the state because componentWillReceiveProps will run regardless if the props changed or not, as per React documentation.
The real question is, should you store something in your state if it's already available as a prop. If you have a list of therapists as a prop, why not simply render it instead of duplicating it and having to keep those two in sync?
If you really have to keep it in the state for whatever reason, you can use componentDidUpdate in which you can compare equality of previous and current props and set the state accordingly.
You need to compare the coming data with this.state.therapists state in componentWillReceiveProps before updating therapists state because every time componentWillReceiveProps is running and you concatenate even if the same data coming.

Categories