0

I have a function that generates an object that I would like to add to my state. I am using react hooks. Here is my code:

const [roomMatches, setRoomMatches] = useState({
                                         "user2":{ "percentMatch":"1.0"},
                                         "user3":{ "percentMatch": ".30"}
                                               })

var newMatch = {
                 survey:{
                            ['percentMatch']: .99
                        }
               }

setRoomMatches([...roomMatches, newMatch]);

My problem is that I keep getting the same error

Uncaught TypeError: roomMatches is not iterable

How can I add to the current state without deleting what is in the state allready?

1
  • 3
    Well roomMatches is an object, but you're trying to spread it into an array. Commented Jan 28, 2020 at 23:36

2 Answers 2

1

It looks like what you're trying to do is merge your newMatch into the existing roomMatches and then update the state. To do that, you'd need to do the following:

const newState = {...roomMatches, ...newMatch};
setRoomMatches(newState);

In the code above, you're attempting to update the state with an array rather than an object (and, as the comment suggests, spreading the object into an array won't work).

Sign up to request clarification or add additional context in comments.

Comments

0

As it was pointed out by Jayce444, you're trying to spread your roomMatches object into the array which is not possible.

I believe you want something like this:

const [roomMatches, setRoomMatches] = useState({
  user2: { percentMatch: '1.0' },
  user3: { percentMatch: '.30' },
});

var newMatch = {
  survey: {
    percentMatch: 0.99,
  },
};

setRoomMatches({ ...roomMatches, newMatch });

P.S. I'm not sure if it is intentional, but you might want to spread newMatch as well when you call setRoomMatches.

Comments

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.