0

On click of a button I want to update my channels array, and add a new channel but it is not working. Here is the function that is executed when the array is updated.

  const channelData = setupChannels(venue !== null ? venue.chatRooms : []); 
  const [channelName, setChannelName] = useState('');
  const [categoryName, setCategoryName] = useState('');
  const [channels, setChannels] = useState(channelData);``` 

const onAddChannelClick  = () => {
    if (channelName === '') {
      return;
    }
    let existingChannels = [...channels];
    let newChannel = {
      key: existingChannels.length,
      name: channelName,
      deletable: true,
      markedForDelete: false,
      category: categoryName
    };
    existingChannels.push(newChannel);
    console.log(newChannel);
    setChannels(existingChannels);
    setChannelName('');
    setCategoryName('');
    setCreateChannel(false);
    console.log(existingChannels);
    console.log(channels);
  };

In the first console log console.log(newChannel); I see my new channel with all the keys and values. When I console.log(existingChannels);I see all the array with my newChannel added to it but all the categories are undefined and when I console.log(channels) my whole newChannel object is not added and all of the categories are undefined.

Can anyone see anything wrong with this code or is the issue most likely coming from somewhere else?

Angela Inniss
  • 359
  • 1
  • 2
  • 18
  • React set states is asynchronous so console logging directly after setting the state will show old values. – Ogiez Jun 08 '20 at 09:16

1 Answers1

1

Not clear of why category is undefined. but you can't console channels immediately after setChannels, as the data wouldn't have updated already.

Use useEffect instead to log the data.. or you would find it updated if you are looping them in the return.

useEffect(() => {
   console.log(channels)
}, [channels]);
Chetan
  • 945
  • 1
  • 5
  • 14