I have two issues, the first one was when I wanted to pass an array of objects from a parent component to a child component, something like this:
function DropdownSome ({options, placeholder, someNum}) {
const [value, setValue] = useState (options)
return (
<Dropdown as = {ButtonGroup}>
<Dropdown.Toggle as = {CustomToggle}>
{placeholder}
</Dropdown.Toggle>
<Dropdown.Menu as = {CustomMenu}>
{value.map ((r, index) =>
<Dropdown.ItemText key = {r.id}>
<Counter
index={index}
someNum={someNum}
...
/>
</Dropdown.ItemText>
)}
</Dropdown.Menu>
</Dropdown>
)
}
export default DropdownSome;
Here I couldn't set an array with useState (hooks) because it didn't finish passing my constant value. Then solve this using the useEffect hook, like this:
useEffect (() => {
setValue (options); // this worked to pass options in value
}, [options])
Then I was able to pass my array to my const value, and I was able to use value within my child component. In this component I need to set a value inside my array (setValue (array[someIndex].qty= someNum)). My second issue now is that the useEffect hook is always updating the value of my array to its initial state and this does not allow me to update my array within my child component (array[someIndex].qty // always set at the initial value). I've only tried running useEffect once like this:
useEffect (() => {
setValue (options); // this doesn't work to pass options in value
}, [])
but doing this, my array again fails to pass to my constant value and I feel like I'm stuck here. I've also tried clearing useEffect so that the setValue only runs once, but useEffect keeps setting my variable to its initial state.
useEffect (() => {
const counterInterval = setInterval (() => {
setValue (options);
});
return () => clearInterval (counterInterval);
}, [options]);
I am new to this and some hook life cycle topics are taking me some time to understand, but I hope someone has gone through something similar who can advise me.
setValue(array[someIndex].qty= someNum)? It's typically a React anti-pattern to store passed props in local component state (as @hellogoodnight points out), but then this leave the door option to you seeming to still want to update the options values. Where doesoptionslive as a source of truth and where are you wanting to update it? - Drew Reese