0

I am trying to add an array to an existing array using react hooks. The only problem I have is everything I try it keeps not filling the array...

const [ residenceFinal, setResidenceFinal ] = useState([]);

I created the the value here and beneath I am trying to add an existing array to residenceFinal.

const predefinedMenuItems = {
      residences: {
            closeOnClick: false,
            setActiveOnClick: true,
            tooltip: "Residences",
            content: <i className='fas fa-city'/>,
            onClick: () => {
                dispatch(getValue(value));
            },
            getContent: (controlledEntity) => {
                const divTitle = "Residence info";

                let res = controlledEntity.info;
                const {data} = res;
                let residencesInfo = [];
                _.isArray(data) ? residencesInfo = data : residencesInfo.push(data);

                let resiFinal = residencesInfo.map(function(el) {
                    var o = Object.assign({}, el);
                    o.isActive = false;
                    return o;
                  })

                setResidenceFinal(resiFinal);
                return <div className="open-data-information-drawer-item residences">
                    <h1>{divTitle}</h1>
                    <div className="open-data-item-information-container">
                        {residenceFinal.map((residence, idx) => {
                            return <div className={"open-data-item-information-container-item "+ (residence.isActive ? 'active' : '') + " item-" + idx}  onClick={ (e) => onClickIdentification(residence, idx)} key={idx}>
                                {getOpenDataLi(residence, "identificatiecode")}
                                {getOpenDataLi(residence, "status")}
                                {getOpenDataLi(residence, "oppervlakte")}
                        }
                            </div>;
                        })}
                    </div>
                </div>;

            }
       }
}

So I have tried alot of variations to add resiFinal to residenceFinal (naming is gonna change when i fixed it btw) but every time I check, the residenceFinal is still empty...

Can somebody help me?

Edit: added where the getContent is used.

const [ drawerContent, setDrawerContent ] = useState(<div></div>);
function handleClick(index, e) {
        const selectedMenuItem = menuItems.find(m => m.id === index);

        setDrawerContent(selectedMenuItem.getContent(openData));
    }
<List.Item >
    <div key={predefinedMenuItemId} onClick={ e => handleClick(predefinedMenuItemId, e)}  className={isMenuItemActive ?  'list-item list-item-' + predefinedMenuItemId  : 'list-item list-item-' + predefinedMenuItemId }></div>
</List.Item >

11
  • Did you consoel.log() the values for residencesInfo adn resiFinal variables like right before setResidenceFinal(resiFinal)? Commented Feb 21, 2020 at 9:41
  • try: setResidenceFinal([...resiFinal]); but correct way to set state is: setResidenceFinal([... residenceFinal, ...resiFinal]); persist the previous state as well. Commented Feb 21, 2020 at 9:42
  • Most likely controlledEntity.info.data is an empty array. Commented Feb 21, 2020 at 9:44
  • 1
    It's not clear what your code is supposed to do. Where is getContent used and when is it called? Also a getter usually is side-effect-free meaning it doesn't change the applications state when called. But that may be just due to bad naming. If your goal is to append resiFinal to the current state then it's just: setResidenceFinal(current => [...current, ...resiFinal]); Commented Feb 21, 2020 at 9:50
  • @trixn I edited my post with where the getContent is used. Commented Feb 21, 2020 at 10:01

3 Answers 3

1

You need to employ Spread Syntax

example of how it works:

var colors = ['red', 'green', 'blue'];
var refColors = [...colors, 'yellow'];
//colors => ['red', 'green', 'blue']
//refColors => ['red', 'green', 'blue', 'yellow']

So for your case

setResidenceFinal(current => [...current, ...resiFinal])
Sign up to request clarification or add additional context in comments.

Comments

0

You can use spread syntax to achieve this:

setResidenceFinal([... residenceFinal, ...resiFinal]);

As told you in my comment above, it's the correct way to set the state, preserving previous state while adding new state. One should never mutate the state directly.

Comments

0

The way you can add array to existing array

  • push() method

  • spread operator

  • concat() method

let array = [1,2];
array.push(...[3,4])
console.log(array)

let array2 = [10,11];
let newArray = [...array2, ...[12,13]];
console.log(newArray)

let array3 = [20,21];
let newArray2 = [22,23].concat(...array3)
console.log(newArray2)

you can add using such ways.

setResidenceFinal([...residenceFinal, ...resiFinal]);

Recommended to use spread operator for updating state in react

1 Comment

While this is correct, push is not good practice to use for state-updates with React as that does mutate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.