Eva
Eva

Reputation: 467

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
});

Upvotes: 9

Views: 12359

Answers (3)

Sardorek Aminjonov
Sardorek Aminjonov

Reputation: 834

The easiest solution would be:

// Redux state
const user = useSelector((state) => state.user);

const [firstName, setFirstName] = useState(user.firstName || '');

Upvotes: 1

Yura  Seniagin
Yura Seniagin

Reputation: 161

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
}: {});

`

Upvotes: 5

Will Jenkins
Will Jenkins

Reputation: 9787

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
});

Upvotes: 4

Related Questions