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
});
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.
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.
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.
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.
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
}: {});
`
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With