Abdelhadi Abdo
Abdelhadi Abdo

Reputation: 412

Redux state and useState not sync

I want to set my reduxState to useState, but the problem is reduxState come after rendering then useState still have null which was got at the first rendering. Expect: reduxState pass every change or update to useState.

    const Account: React.FC<Props> = ({ logInAction, userDataStore }) => {
        const [userValues, setUserValues] = useState<User>(userDataStore as User);
        return (
         <Text>
             {/*
              this data (userValues) still null 
              despite userDataStore 
              is changed and has Data
             */}
          Fullname: {userValues.fullName}  
         </Text>
        );
        .
        .
        .
        export default connector(Account);

I know using redux state directly work for me:

userDataStore.fullName
     <Text>
                   {/* fullName: {userValues.fullName} */} ---> not work always null
                   fullName: {userDataStore.fullName} ---> this work good

              </Text>
    );

But me i want to use useState. Any help please ?

I will be very appreciated .

Upvotes: 1

Views: 919

Answers (1)

Harald Gliebe
Harald Gliebe

Reputation: 7554

Not sure what is the reason you don't want to use the reduxState and use the useState hook, but you could achieve synchronisation between reduxState and the user values by adding a useEffect hook:

    const [userValues, setUserValues] = useState<User>(userDataStore as User);
    useEffect(() => {
      setUserValues(userDataStore as User)
    }, [userDataStore]);
    ...

This will set the userValues whenever the userDataStore changes.

Upvotes: 4

Related Questions