Himanshu Rahi
Himanshu Rahi

Reputation: 301

useEffect Setting Redux State multiple Times

Am new in React and am trying to create an Chat App and in my app there is section of channels now here what i done for fetching channel

const [Channels, setChannelState] = React.useState([]);

  const ref = firebase.database();
  const loadedChannels = [];

  React.useEffect(() => {
    ref.ref("channels").on("child_added", snap => {
      loadedChannels.push(snap.val());
      setChannelState([...loadedChannels]);
    });
  }, []);

whenever new channel added it updates the local state

so my problem is here i want when page loads it basically get first channel from Channels State Array i.e Channels and set it to redux global state

here is my dispatcher

const mapDispatchToProps = dispatch => {
  return {
    SetFirstChannel: channel => {
      dispatch({ type: "SET_FIRST_CHANNEL", payload: channel });
    }
  };
};

and in my reducer:

const iState = {
  currentChannel: ""
};

export const rootReducer = (state = iState, action) => {
  return {
    currentChannel: action.payload
  };
};

now how can i get the first element from channels array and store into the redux

here what i have done so far.. https://codesandbox.io/embed/quiet-wind-g9zxx but this cause setting redux state multiple times

Upvotes: 0

Views: 945

Answers (1)

Praneeth Paruchuri
Praneeth Paruchuri

Reputation: 1032

If you just want the first channel every-time and only update it if the first channel changes, something like this should work:

React.useMemo(() => props.SetFirstChannel(Channels[0]), [Channels[0]]);

I set this up locally and checked. Let me know if it works. Cheers!

Upvotes: 1

Related Questions