reactjs: setState being called twice in a function called once? why? - javascript

EDIT: since the code snip does not reproduce the bug - here is a link to the github repo: (code is far FAR from complete)
https://github.com/altruios/clicker-game
I have run it on two computers now - both with the same behavior the code snip doesn't show.
//interestingly enough, this works just fine, where the same code I run locally has the doubling.
//when I comment out ALL other code except for this code I STILL get the error locally
//at this point the only difference is import export of components... here they are in one file.
//below is original code from file (
/*
FILE::::Clicker.js
import React from 'react';
function Clicker(props)
{
return(
<div>
{props.name}
<button
name={props.name}
onClick={props.HandleClick}
data-target={props.subjectsOfIncrease}>
{props.name} {props.value}
</button>
</div>
)
}
export default Clicker;
FILE:: Resouce.js
import React from 'react';
function Resource(props)
{
return(
<div>
{props.name} and {props.amount || 0}
</div>
)
}
export default Resource;
*/
//besides the import/export and seprate files - code is the same. it works in here, does not work locally on my machine.
const gameData = {
clickerData: [{
name: "grey",
subjectsOfIncrease: ["grey"],
isUnlocked: true,
value: 1
}],
resourceData: [{
name: "grey",
resouceMax: 100,
isUnlocked: true,
changePerTick: 0,
counterTillStopped: 100,
amount: 0
}]
}
class App extends React.Component {
constructor() {
super();
this.state = {
resources: gameData.resourceData,
clickers: gameData.clickerData
};
this.gainResource = this.gainResource.bind(this);
}
gainResource(event) {
console.count("gain button");
const name = event.target.name;
this.setState((prevState) => {
const newResources = prevState.resources.map(resource => {
if (resource.name === name) {
resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
}
return resource;
});
console.log(prevState.resources.find(item => item.name === name).amount, "old");
console.log(newResources.find(item => item.name === name).amount, "new");
return {
resources: newResources
}
});
}
render() {
const resources = this.state.resources.map(resourceData => {
return (
<Resource
name = {resourceData.name}
resouceMax = {resourceData.resourceMax}
isUnlocked = {resourceData.isUnlocked}
changePerTick = {resourceData.changePerTick}
counterTillStopped = {resourceData.countTillStopped}
amount = {resourceData.amount}
key = {resourceData.name}
/>
)
})
const clickers = this.state.clickers.map(clickerData => {
return (
<Clicker
name = {clickerData.name}
HandleClick = {this.gainResource}
value = {clickerData.amount}
key = {clickerData.name}
/>
)
})
return (
<div className = "App" >
{resources}
{clickers}
</div>
)
}
}
function Resource(props) {
return <div > {props.name} and {props.amount || 0} </div>
}
function Clicker(props) {
return (
<div > {props.name}
<button name = {props.name} onClick = {props.HandleClick}>
{props.name} {props.value}
</button>
</div>
)
}
const root = document.getElementById('root');
ReactDOM.render( <App / >,root );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
so I'm building a clicker game to learn react, and something I don't understand why this code is behaving the way it does:
in the main app I have this function:
gainResource(event)
{
console.count("gain button");
const name = event.target.name;
this.setState( (prevState)=>
{
const newResources = prevState.resources.map(resource=>
{
if(resource.name === name)
{
resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
}
return resource;
});
console.log(prevState.resources.find(item=>item.name===name).amount, "old");
console.log(newResources.find(item=>item.name===name).amount, "new");
return {resources: newResources}
});
}
that console.count runs a single time... but I get 2 'old and new' pairs. as if setState is running twice in this function which only runs once?
the console.output is:
App.js:64 gain button: 1
App.js:76 1 "old"
App.js:77 1 "new"
App.js:76 2 "old"
App.js:77 2 "new"
so it looks like the function is running once. but the set state is being run twice?
the symptoms are that it counts up by 2. but also the initial state of amount is 0, not 1, as seen in the gamedata.json
resourceData:
[
{
name:"grey",
resouceMax:100,
isUnlocked:true,
changePerTick:0,
counterTillStopped:100,
amount:0
},{etc},{},{}],
clickerData:
[
{
name:"grey",
subjectsOfIncrease:["grey"],
isUnlocked:true,
value:1
},{etc},{},{}]
i don't think the rest of the code I'm about to most is relevant to this behavior, but I don't know react yet, so I don't know what I'm missing: but this is how I'm generating the clicker button:
const clickers = this.state.clickers.map(clickerData=>
{
return(
<Clicker
name={clickerData.name}
HandleClick = {this.gainResource}
value = {clickerData.amount}
key={clickerData.name}
/>
)
})
and in the clicker.js functional component I'm just returning this:
<div>
{props.name}
<button name={props.name} onClick={props.HandleClick}>
{props.name} {props.value}
</button>
</div>
the function is bound to this in the constructor... I don't understand why this is running setState twice inside a function that's called once.
I've also tried:
<div>
{props.name}
<button name={props.name} onClick={()=>props.HandleClick}> //anon function results in no output
{props.name} {props.value}
</button>
</div>

This is an intended behavior of a setState(callback) method wrapped in a <React.Strict> component.
The callback is executed twice to make sure it doesn't mutate state directly.
as per: https://github.com/facebook/react/issues/12856#issuecomment-390206425
In the snippet, you create a new array, but the objects inside of it are still the same:
const newResources = lastResources.map(resource => {
if(resource.name === name){
resource.amount = Number(resource.amount) + 1
}
return resource;
}
You have to duplicate each object individually:
const newResources = lastResources.map(resource => {
const newObject = Object.assign({}, resource)
if(resource.name === name){
newObject.amount = Number(newObject.amount) + 1
}
return newObject;
}

BEST ANSWER:
I was using create-react-app. and my App Component was wrapped in Strict mode... which fires setState twice... which perfectly explains why this was not reproducible on the code snip, and why the function was being called once, yet setState was called twice.
removing strict mode fixed the issue completely.

As long as you didn't provide us a runnable example I've one doubt about what could be happened and let's see if it works.
What I can see is in the gainResource function and specially in this line resource.amount = Number(resource.amount) + 1 you're trying to update the state without using setState which is not recommended by React Documentation
Please instead try first to assign a const myRessource = ressource then return myRessource instead.
gainResource(event)
{
console.count("gain button");
const name = event.target.name;
this.setState( (prevState)=>
{
const newResources = prevState.resources.map(resource=>
{
const myRessource = ressource;
if(myRessource.name === name)
{
myRessource.amount = Number(myRessource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
}
return myRessource;
});
console.log(prevState.resources.find(item=>item.name===name).amount, "old");
console.log(newResources.find(item=>item.name===name).amount, "new");
return {resources: newResources}
});
}

okay... so after some hair pulling... I found out a way that works... but I DON'T think this is 'best practice' but it now works for me when I write this:
gainResource(event)
{
const name = event.target.name;
const lastResources = this.state.resources.slice();
const newResources = lastResources.map(resource=>
{
if(resource.name === name)
{
resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
}
return resource;
});
this.setState({resources: newResources});
}
vs
gainResource(event)
{
console.count("gain button");
const name = event.target.name;
this.setState( (prevState)=>
{
const newResources = prevState.resources.map(resource=>
{
if(resource.name === name)
{
resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
}
return resource;
});
console.log(prevState.resources.find(item=>item.name===name).amount, "old");
console.log(newResources.find(item=>item.name===name).amount, "new");
return {resources: newResources}
});
}
that setState without the function of prevState is called once... whereas with the prevState it's called twice... why?
so I still don't understand why setState using a function with prevState is causing two function calls within a function that's called only once... I have read that I should be using prev state as this.state.resources.slice(); just takes an 'untimed snapshot' and could be unreliable. is this true... or is this methodology acceptable?
this is AN answer to anyone else struggling with this. hopefully a better answer can be posted after this enlightenment to what might be happening.

Ok took me a bit of time to figure this out. As others have mentioned your call back needs to be idempotent. the thing to realise here is that react passes the same state object instance into your callback each time it calls it. hence if you change the state object on the first call it will be different on the second call and your callback function will not be idempotent.
this.setState((state) =>
{
//state.counter will have the same value on the first and second
//time your callback is called
return { counter: state.counter + 1};
});
this.setState((state) =>
{
//state.counter will have a value of n+1 the second time it is called
//because you are changing the sate object. This will have the net effect
//of incrementing state.counter by 2 each time you call this.setState!!
state.counter = state.counter + 1;
return { counter: state.counter};
});
The above is probably obvious but this situation becomes less obvious when dealing with arrays. for eg
this.setState((state) =>
{
//even though we are creating a new array, the
//objects in the array have just been copied
//so changing them is probelmatic
newArray = [...state.someArray];
//this is ok as we are replacing the object at newArray[1]
newArray[1] = {objectField : 1};
//this is not ok
newArray[1].objectField = 1;
return { someArray: newArray};
});

Related

Function execution uses old prop values instead of new prop values

I'm using React functional components and here are my codes:
Parent component function:
const calculateAPR = async (val) => {
setIsAprLoading(true);
try {
if (val.addr !== "" && val.date !== null) {
const totalStaking = await someEP.getSomeData(val.addr);
val.staked = totalStaking;
setResData((prevState) => {
return ({
...prevState,
aprRes: val
})
})
setRenderApr(true);
setIsAprLoading(false);
}
else {
setRenderApr(false);
alert(Constants.ADDR_N_DATE_ERR);
}
}
catch (err) {
setRenderApr(false);
console.log(err);
alert(Constants.ADDR_NO_DATA);
}
finally {
setIsAprLoading(false);
}
}
...
return (
...
<QueryAprField text={Constants.CALC_APR_HEADER} onFunction={calculateAPR} isLoading={isAprLoading} />
<CalculateAprField resData={resData.aprRes} onRender={renderApr} />
...
)
Child component 1:
function QueryAprField(props) {
...
const handleQuery = () => {
const verify = verifyDelegatorAddress();
if (verify) {
props.onFunction(queryValue);
}
else {
alert(Constants.ENTER_VALID_DEL_ADDR);
}
}
...handles taking in user inputs and passing it to parent component...
}
Child component 2:
function CalculateAprField(props) {
const aprRes = props.resData;
...
const renderCard = () => {
if (renderData == true) {
const aprInput = setAprInputs(aprRes);
const { staked } = extractAprInput(aprInput);
const apr = parseFloat(calculateAPR(staked, accrued, withdrawn, numOfDays).toFixed(5));
if (isNaN(apr)) {
//How to reset aprRes and ensure that its not using old values
return alert(Constants.APR_AUTO_ERR)
}
return (
<Paper elevation={4}>
...some html and css...
</Paper>
)
}
}
return (
<Box>
{renderCard()}
</Box>
)
I'm trying to enable a situation where, after calculateAPR in the parent component is executed, some data will be passed to child component 2; and in child component 2 in the renderCard function, if the variable apr in child component 2 is NaN then an alert will be triggered. However, the problem I'm facing now is that after the alert is triggered, and when I put in new values and execute calculateAPR again, child component 2 seems to use the old values first before using the new values that are passed down from the parent component. So in other words, I get the alert first and then it uses the new values that are being passed down.
How can I enable the aprRes variable in child component 2, to reset its value after the alert is thrown? So that the alert is not thrown twice?
There is no need to reset the value. component rerenders only on props change.
I see the problem could be with this line. const aprInput = setAprInputs(aprRes); React setState doesn't return anything. Please change it to below and try once.
setAprInputs(aprRes);
(or)
if aprInput is not used anywhere else better extract from aprRes only.
const { staked } = extractAprInput(aprRes);
Incase if setAprInputs is not a setState rather a user-defined function, ensure it is a synchronous function and console.log after the call.
hope this gives you some insight to debug.

How to sync a JS class to a component's state in React?

I am completing a technical challenge and came across a scenario I never had to deal with before.
I am asked to code up a shopping cart that has a UI that represents basic checkout data like order total, current items in cart, etc.
One of the requirements states I need to implement a Checkout class that can be instantiated:
const checkout = new Checkout();
And I should be able to obtain basic info from it like:
const total = checkout.total();
And add items to the cart through it:
checkout.add(product.id);
What makes this a tricky thing to solve is that I can't think of a clean "DRY" way of implementing it into the UI. This is mainly because any updates in the checkout class will not trigger any re-renders since it's not part of the state. I would usually use state variables for this.
I tried binding state variables to parameters in the checkout class like:
const [total, setTotal] = useState();
useEffect(()=>{
setTotal(checkout.total)
}, [checkout.total])
But checkout.total is only the reference to the method, so it never changes so I do not get the binding I want.
Trying out other stuff I managed to put together a "solution" but I question whether it is a good pattern.
I basically pass a callback to the checkout class which is called whenever the cart is updated. The callback is a state variable's setter, so:
const [cart, setCart] = useState<string[]>(checkout.cart);
checkout.callback = setCart;
Then inside the add method:
add(productId) {
// Some code...
this.callback([...this.cart]);
}
What this grants is that the cart state variable is updated whenever the checkout class has changes in its parameters. So it fires a rerender on the Cart component and all of its children that have props being passed down. Therefore I get a synced UI.
The thing is I kind of don't need the cart variable other than for forcing re-renders. I can get the cart info directly from the checkout class which is what I do. But for it to be reflected in the UI I need some state variable to be updated. It could even be a counter, I only went for cart instead of a counter to make it more coherent I guess.
Am I overcomplicating things here? Is there a pattern I am missing that is used for this scenarios? How does one usually interact with an instantiated class and ensures the UI is somehow updated from changes to the class?
EDIT (adding missing info):
The Checkout class needs to implement the following interface:
interface Checkout {
// ...
// Some non relevant properties methods
// ...
add(id: number): this;
}
So it is explicitly asked that the add method returns this (in order to allow function chaining).
mixing of patterns
Using OOP instances with methods that mutate internal state will prevent observation of a state change -
const a = new Checkout()
const b = a // b is *same* state
console.log(a.count) // 0
a.add(item)
console.log(a.count) // 1
console.log(a == b) // true
console.log(a.count == b.count) // true
React is a functional-oriented pattern and uses complimentary ideas like immutability. Immutable object methods will create new data instead of mutating existing state -
const a = new Checkout()
const b = a.add(item) // b is *new* state
console.log(a.count) // 0
console.log(b.count) // 1
console.log(a == b) // false
console.log(a.count == b.count) // false
In this way, a == b is false which effectively sends the signal to redraw this component. So we need a immutable Checkout class, where methods return new state instead of mutating existing state -
// Checkout.js
class Checkout {
constructor(items = []) {
this.items = items
}
add(item) {
return new Checkout([...this.items, item]) // new state, no mutation
}
get count() {
return this.items.length // computed state, no mutation
}
get total() {
return this.items.reduce((t, i) => t + i.price, 0) // computed, no mutation
}
}
export default Checkout
demo app
Let's make a quick app. You can click the 🍐 and 🥨 buttons to add items to the cart. The app will show the correct count and total as well as the individual items -
App component preview
Now "syncing" the class to the component is just using ordinary React pattern. Use your class and methods directly in your componenets -
import Checkout from "./Checkout.js"
import Cart from "./Cart.js"
function App({ products = [] }) {
const [checkout, setCheckout] = React.useState(new Checkout)
const addItem = item => event =>
setCheckout(checkout.add(item))
return <div>
{products.map(p =>
<button key={p.name} onClick={addItem(p)}>{p.name}</button>
)}
<b>{checkout.count} items for {money(checkout.total)}</b>
<Cart checkout={checkout} />
</div>
}
const data =
[{name: "🍐", price: 5}, {name: "🥨", price: 3}]
const money = f =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(f)
A simple Cart component uses JSON.stringify to quickly visualize each item -
// Cart.js
function Cart({ checkout }) {
return <pre>{JSON.stringify(checkout, null, 2)}</pre>
}
export default Cart
Run the demo below to verify the result in your browser -
class Checkout {
constructor(items = []) {
this.items = items
}
add(item) {
return new Checkout([...this.items, item])
}
get count() {
return this.items.length
}
get total() {
return this.items.reduce((t, i) => t + i.price, 0)
}
}
function App({ products = [] }) {
const [checkout, setCheckout] = React.useState(new Checkout)
const addItem = item => event =>
setCheckout(checkout.add(item))
return <div>
{products.map(p =>
<button key={p.name} onClick={addItem(p)}>{p.name}</button>
)}
<b>{checkout.count} items for {money(checkout.total)}</b>
<Cart checkout={checkout} />
</div>
}
const money = f =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(f)
function Cart({ checkout }) {
return <pre>{JSON.stringify(checkout, null, 2)}</pre>
}
const data = [{name: "🍐", price: 5}, {name: "🥨", price: 3}]
ReactDOM.render(<App products={data} />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>
Hmm, looks like you need to share the state. The first solution that came to my mind is just to use the Class component. You can use force rerender while you need and write more custom logic without useEffect hacks.
The second solution is more clear IMO. It uses an Observer pattern. You need to add a subscription to your Checkout class. So basically.
useEffect(() => {
const subscription = (newState) => setState(newState)
const instance = new Checkout()
instance.subcribe(subscription)
return instance.unsubcribe(subscription)
}, [setState])
Since setState is immutable, this hook will be run only once.
Your idea is correct, you need somehow to start re-render to sync state of checkout object and state of a component.
E.g. you may do it by context and force update (in case if you do not want to duplicate data in object and state):
const CheckoutContext = React.createContext();
const checkout = new Checkout();
const CheckoutProvider = ({ children }) => {
// init force update, just to start re-render
const [ignored, forceUpdate] = React.useReducer((x) => x + 1, 0);
const add = (a) => {
checkout.add(a);
forceUpdate();
};
const total = checkout.total();
const value = { add, total };
return (
<CheckoutContext.Provider value={value}>
{children}
</CheckoutContext.Provider>
);
};
const Child = () => {
const v = React.useContext(CheckoutContext);
console.log(v.total);
return <button onClick={() => v.add(100)}>Click</button>;
};
export default function App() {
return (
<div className="App">
<CheckoutProvider>
<Child />
</CheckoutProvider>
</div>
);
}
You can make a Cart class that allows for observers to be notified when something important happens. To make it available for the react components, provide an instance of it with a context, and use a stateful hook to notify components by setting the state through the observer function.
Here we go:
First, we need a Cart class that notifies observers when something happens
export class Cart {
constructor() {
this.products = [];
this.subscribers = new Set();
}
subscribe = (notifyMe) => {
this.subscribers.add(notifyMe);
};
unSubscribe = (notifyMe) => {
this.subscribers.delete(notifyMe);
};
addToCart = (product) => {
this.products = [...this.products, product];
this.notify();
};
removeFromCart = (product) => {
this.products = this.products.filter(product);
this.notify();
};
notify = () => {
this.subscribers.forEach((n) => n(this.products));
};
}
We will expose this through the react tree with a context, so lets make one
const CartContext = React.createContext();
export const CartProvider = ({ children, cart }) => {
return <CartContext.Provider value={cart}>{children}</CartContext.Provider>;
};
Now for the trick! A hook that will update its state using the carts observer pattern, thereby notifying the component that uses it.
export const useCart = () => {
const cart = React.useContext(CartContext);
const [content, r] = React.useState();
React.useEffect(() => {
const notify = (productsInCart) => r(productsInCart);
cart.subscribe(notify);
cart.notify();
return () => cart.unSubscribe(notify);
}, [cart, r]);
return {
addToCart: cart.addToCart,
removeFromCart: cart.removeFromCart,
content
};
};
Note that it can be worth to update after subscribing.
Now we have our library set up, we can make some components. So here's where we instantiate the Cart class. We make a new Cart, and let the provider provide that instance
const cart = new Cart();
export default function App() {
return (
<div className="App">
<CartProvider cart={cart}>
<CartCounter />
<h1>Welcome to the shop</h1>
<h2>start putting stuff in the cart!</h2>
<Catalog />
<button
onClick={() => {
// this will still notify components
cart.addToCart({ foo: "bar" });
}}
>
add product by directly manipulating class instance
</button>
</CartProvider>
</div>
);
}
Here are the other components
const Catalog = () => {
const getProducts = async () =>
await fetch(
"https://random-data-api.com/api/commerce/random_commerce?size=6"
).then((r) => r.json());
const [products, setProducts] = React.useState();
React.useEffect(() => {
getProducts().then(setProducts);
}, []);
if (!products) {
return null;
}
return (
<ul
style={{
listStyle: "none",
display: "grid",
gridTemplateColumns: "50% 50%"
}}
>
{products.map((product) => (
<Item key={product.uid} product={product} />
))}
</ul>
);
};
const Item = ({ product }) => {
const { addToCart } = useCart();
const addProductToCart = () => addToCart(product);
return (
<li>
<article
style={{
maxWidth: 200,
border: "1px solid black",
margin: 10,
padding: 10
}}
>
<h4>{product.product_name}</h4>
<div>
<div>$ {product.price}</div>
<button onClick={addProductToCart}>add to cart</button>
</div>
</article>
</li>
);
};
const CartCounter = () => {
const { content } = useCart();
return <div>items in cart: {content?.length || 0}</div>;
};
This can be a pretty handy pattern, and can be taken pretty far (e.g. React Query works like this).
CodeSandbox link
I read with interest most of the answers, and I found them pretty explicative and comprehensive, especially the extensive example of the observer pattern.
I used the same approach to handle a similar need, without having to implement all the pattern and it makes use of the 'EventEmitter' class.
This way you can subscribe your React UI to several different type of events, olle's example would become something like this:
export class Cart extends EventEmitter {
constructor() {
super();
this.products = [];
}
addToCart = (product) => {
this.products = [...this.products, product];
this.emit("CART_UPDATE", this.products)
};
removeFromCart = (product) => {
this.products = this.products.filter(product);
this.emit("CART_UPDATE", this.products)
};
}
And in React you'd just need a custom hook or just an effect placed on top where you can place your event listeners:
export default function App() {
const cartRef = useRef(new Cart())
const [items, setItems] = useState([])
useEffect(()=>{
const cart = cartRef.current
cart.on("CART_UPDATE", setItems)
return () => cart.removeListener("CART_UPDATE", setItems)
}, []) //
return (
<div className="App">
<div>{items.map(it => item.id)}</div>
<button
onClick={() => {
// this will still notify components
cart.addToCart({ id: "bar" });
}}
>
add product by directly manipulating class instance
</button>
</div>
);
}
I think it is perfectly reasonable to send a callback to the object and then call that callback when it is needed. If you don't want to add any unnecessary data, then don't:
add(productId) {
// Some code...
this.callback();
}
checkout.callback = () => {
setTotal(checkout.total);
}

Function only being passed to React child component once

I've got something I don't understand here. I'm creating a hierarchy of React functional components like so:
const ContainerComponent = () => {
const [total, setTotal] = useState(initialValue);
const updateFunction = () => { console.log('It got called'); }
return (
<EntryComponent updateFunction={updateFunction} />
);
}
const EntryComponent = ({updateFunction}) => {
const services = [{}, {}, {}];
return (
{services.map((service) => <ServiceComponent updateFunction={updateFunction} />}
);
}
const ServiceComponent = ({updateFunction}) => {
return (
<input type='checkbox' onChange={updateFunction} ></input>
);
}
So the idea is that the function gets passed all the way to the ServiceComponent and attached to the checkbox for each component. On change the function should fire, running the code and updating the total value in the ContainerComponent. Problem is that this isn't happening properly and the function seems only to be passed to the first ServiceComponent instance. If I drop a console.log(updateFunction) into ServiceComponent I see the function logged for the first component, and undefined for the remaining two. This is strange even for JavaScript. Can anyone shed any light as to what is going on? As far as I understand the function should be able to be passed like any other variable, and each ServiceComponent should have it to use when needed. Indeed, if I pass a second property to the child, an object or a primitive like an integer it comes through just fine on every child component. Why is this not occurring for my function, and how do I fix it?
Edit: I see the problem, and the problem is I'm not as smart as I think I am. In the condensed version I put here everything is being supplied to the child components in the same loop, but in the actual project the child components are created in multiple places and I neglected to pass the function property to all of them. Which is mind mindbogglingly stupid on my part. I'm leaving the question here as many of you have posted replies, for which I'm grateful.
Programming is hard, I think I need a better brain.
I tried refactoring your code to this
const ContainerComponent = () => {
const [total, setTotal] = useState(0);
const updateFunction = (e) => {
console.log("update total stuff happens here");
console.log(e);
};
return <EntryComponent updateFunction={updateFunction} />;
};
const EntryComponent = ({ updateFunction }) => {
const services = ["one", "two", "three"];
return (
<>
{services.map((service) => (
<ServiceComponent updateFunction={updateFunction} />
))}
</>
);
};
const ServiceComponent = ({ updateFunction }) => (
<input type="checkbox" onChange={updateFunction}></input>
);
and it works just fine.
Try also using a react fragment in your entry component.

React | Adding and deleting object in React Hooks (useState)

How to push element inside useState array AND deleting said object in a dynamic matter using React hooks (useState)?
I'm most likely not googling this issue correctly, but after a lot of research I haven't figured out the issue here, so bare with me on this one.
The situation:
I have a wrapper JSX component which holds my React hook (useState). In this WrapperComponent I have the array state which holds the objects I loop over and generate the child components in the JSX code. I pass down my onChangeUpHandler which gets called every time I want to delete a child component from the array.
Wrapper component:
export const WrapperComponent = ({ component }) => {
// ID for component
const { odmParameter } = component;
const [wrappedComponentsArray, setWrappedComponentsArray] = useState([]);
const deleteChildComponent = (uuid) => {
// Logs to array "before" itsself
console.log(wrappedComponentsArray);
/*
Output: [{"uuid":"acc0d4c-165c-7d70-f8e-d745dd361b5"},
{"uuid":"0ed3cc3-7cd-c647-25db-36ed78b5cbd8"]
*/
setWrappedComponentsArray(prevState => prevState.filter(item => item !== uuid));
// After
console.log(wrappedComponentsArray);
/*
Output: [{"uuid":"acc0d4c-165c-7d70-f8e-d745dd361b5",{"uuid":"0ed3cc3-
7cd-c647-25db-36ed78b5cbd8"]
*/
};
const onChangeUpHandler = (event) => {
const { value } = event;
const { uuid } = event;
switch (value) {
case 'delete':
// This method gets hit
deleteChildComponent(uuid);
break;
default:
break;
}
};
const addOnClick = () => {
const objToAdd = {
// Generate uuid for each component
uuid: uuid(),
onChangeOut: onChangeUpHandler,
};
setWrappedComponentsArray(wrappedComponentsArray => [...wrappedComponentsArray, objToAdd]);
// Have also tried this solution with no success
// setWrappedComponentsArray(wrappedComponentsArray.concat(objToAdd));
};
return (
<>
<div className='page-content'>
{/*Loop over useState array*/}
{
wrappedComponentsArray.length > 0 &&
<div>
{wrappedComponentsArray.map((props) => {
return <div className={'page-item'}>
<ChildComponent {...props} />
</div>;
})
}
</div>
}
{/*Add component btn*/}
{wrappedComponentsArray.length > 0 &&
<div className='page-button-container'>
<ButtonContainer
variant={'secondary'}
label={'Add new component'}
onClick={() => addOnClick()}
/>
</div>
}
</div>
</>
);
};
Child component:
export const ChildComponent = ({ uuid, onChangeOut }) => {
return (
<>
<div className={'row-box-item-wrapper'}>
<div className='row-box-item-input-container row-box-item-header'>
<Button
props={
type: 'delete',
info: 'Deletes the child component',
value: 'Delete',
uuid: uuid,
callback: onChangeOut
}
/>
</div>
<div>
{/* Displays generated uuid in the UI */}
{uuid}
</div>
</div>
</>
)
}
As you can see in my UI my adding logic works as expected (code not showing that the first element in the UI are not showing the delete button):
Here is my problem though:
Say I hit the add button on my WrapperComponent three times and adds three objects in my wrappedComponentsArray gets rendered in the UI via my mapping in the JSX in the WrapperComponent.
Then I hit the delete button on the third component and hit the deleteChildComponent() funtion in my parent component, where I console.log my wrappedComponentsArray from my useState.
The problem then occurs because I get this log:
(2) [{…}, {…}]
even though I know the array has three elements in it, and does not contain the third (and therefore get an undefined, when I try to filter it out, via the UUID key.
How do I solve this issue? Hope my code and explanation makes sense, and sorry if this question has already been posted, which I suspect it has.
You provided bad filter inside deleteChildComponent, rewrite to this:
setWrappedComponentsArray(prevState => prevState.filter(item => item.uuid !== uuid));
You did item !== uuid, instead of item.uuid !== uuid
Please try this, i hope this works
const deleteChildComponent = (uuid) => {
console.log(wrappedComponentsArray);
setWrappedComponentsArray(wrappedComponentsArray.filter(item => item !== uuid));
};
After update
const deleteChildComponent = (uuid) => {
console.log(wrappedComponentsArray);
setWrappedComponentsArray(wrappedComponentsArray.filter(item => item.uuid !== uuid)); // item replaced to item.uuid
};
Huge shoutout to #Jay Vaghasiya for the help.
Thanks to his expertise we managed to find the solution.
First of, I wasn't passing the uuid reference properly. The correct was, when making the objects, and pushing them to the array, we passed the uuid like this:
const addOnClick = () => {
const objToAdd = {
// Generate uuid for each component
uuid: uuid(),
parentOdmParameter: odmParameter,
onChangeOut: function(el) { onChangeUpHandler(el, this.uuid)}
};
setWrappedComponentsArray([...wrappedComponentsArray, objToAdd]);
};
When calling to delete function the function that worked for us, was the following:
const deleteChildComponent = (uuid) => {
setWrappedComponentsArray(item => item.filter(__item => __item.uuid !== uuid)); // item replaced to item.uuid
};

React multiple callbacks not updating the local state

I have a child component called First which is implemented below:
function First(props) {
const handleButtonClick = () => {
props.positiveCallback({key: 'positive', value: 'pos'})
props.negativeCallback({key: 'negative', value: '-100'})
}
return (
<div><button onClick={() => handleButtonClick()}>FIRST</button></div>
)
}
And I have App.js component.
function App() {
const [counter, setCounter] = useState({positive: '+', negative: '-'})
const handleCounterCallback = (obj) => {
console.log(obj)
let newCounter = {...counter}
newCounter[obj.key] = obj.value
setCounter(newCounter)
}
const handleDisplayClick = () => {
console.log(counter)
}
return (
<div className="App">
<First positiveCallback = {handleCounterCallback} negativeCallback = {handleCounterCallback} />
<Second negativeCallback = {handleCounterCallback} />
<button onClick={() => handleDisplayClick()}>Display</button>
</div>
);
}
When handleButtonClick is clicked in First component it triggers multiple callbacks but only the last callback updates the state.
In the example:
props.positiveCallback({key: 'positive', value: 'pos'}) // not updated
props.negativeCallback({key: 'negative', value: '-100'}) // updated
Any ideas?
Both are updating the state, your problem is the last one is overwriting the first when you spread the previous state (which isn't updated by the time your accessing it, so you are spreading the initial state). An easy workaround is to split counter into smaller pieces and update them individually
const [positive, setPositive] = useState('+')
const [negative, setNegative] = useState('-')
//This prevents your current code of breaking when accessing counter[key]
const counter = { positive, negative }
const handleCounterCallback = ({ key, value }) => {
key === 'positive' ? setPositive(value) : setNegative(value)
}
You can do that but useState setter is async like this.setState. If you want to base on the previous value you should use setter as function and you can store it in one state - change handleCounterCallback to
const handleCounterCallback = ({key,value}) => {
setCounter(prev=>({...prev, [key]: value}))
}
and that is all. Always if you want to base on the previous state use setter for the state as function.
I recommend you to use another hook rather than useState which is useReducer - I think it will be better for you

Categories

Resources