Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we use redux state in useState to set initial values

I am trying to use redux value to set an initial state of react component using useState.when I am trying to set the state of setIsStar it says currentChannelName is null. How can I avoid this? or is there any other way

const currentChannel = useSelector(state => state.channel.currentChannel);
   const currentChannelName = currentChannel.name;


  const [isStar, setIsStar] = useState({
    [currentChannelName]: true
  });
like image 876
Eva Avatar asked Jul 12 '19 15:07

Eva


People also ask

How do I set Redux state to initial state?

You can set it at the reducers . Reducers can also set initialState by looking at the incoming state argument (which would be undefined if createStore is not called with initialState ) and returning the values they would like to use as default.

How do you set the initial store value in Redux?

There are two main ways to initialize state for your application. The createStore method can accept an optional preloadedState value as its second argument. Reducers can also specify an initial value by looking for an incoming state argument that is undefined , and returning the value they'd like to use as a default.

How do I change my initial state of useState?

To set a conditional initial value for useState in React:Pass a function to the useState hook. Use a condition to determine the correct initial value for the state variable. The function will only be invoked on the initial render.

Can you use Redux with useState?

It is totally fine to use a mix of React component state and Redux state. You might for example use non-critical UI state inside React components, like if a checkbox is checked or not.


2 Answers

Possible solution is to combine it with useEffect:

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;

useEffect(() => {
    if(currentChannelName) {
        setIsStar({[currentChannelName]: true});
    }
}, [currentChannelName]); // listen only to currentChannelName changes

const [isStar, setIsStar] = useState(currentChannelName ? {
    [currentChannelName]: true
}: {});

`

like image 105
Yura Seniagin Avatar answered Oct 31 '22 18:10

Yura Seniagin


You should avoid this as it dilutes your state across two separate domains.

Keep app-wide state in your redux store, keep local component state in your components.

If you really do want to do this, you'll probably just have to deal with the initial case where your component has mounted but the store is not populated with the data you need.

const currentChannel = useSelector(state => state.channel.currentChannel);
const currentChannelName = currentChannel.name;

const [isStar, setIsStar] = useState(currentChannelName && {
  [currentChannelName]: true
});
like image 36
Will Jenkins Avatar answered Oct 31 '22 17:10

Will Jenkins